Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a simple to understand explanation, what is Runnable in Java? [closed]

Tags:

java

runnable

What is "runnable" in Java, in layman's terms? I am an AP programming student in high school, whose assignment is to do research, or seek out from others what "runnable" is (we are just getting into OOP, and haven't touched threads yet).

like image 732
user1809295 Avatar asked Nov 11 '12 00:11

user1809295


People also ask

What is runnable in Java?

Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is no need of subclassing a Thread when a task can be done by overriding only run() method of Runnable.

How do I close runnable?

You can call cancel() on the returned Future to stop your Runnable task.

How is a runnable defined?

Definition of runnable : capable of being run especially : suitable to be hunted runnable stag.


1 Answers

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {      public void run() {          // do stuff here      } } 

And then use it like this:

Thread t = new Thread(new MyRunnableTask()); t.start(); 

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {     public void run() {         // stuff here     } }); t.start(); 

This is similar to the above, only you don't create another named class.

like image 128
opatut Avatar answered Sep 17 '22 18:09

opatut