Creating threads

Threads are objects in the Java language. They can be created using the following mechanisms:

  • Create a class that implements the Runnable interface
  • Create a class that extends the Thread class

There are two ways to create a Runnable object. The first way is to create a class that implements the Runnable interface as follows:

public class ThreadExample {
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
}
}
class MyThread implements Runnable {
private static final Logger LOGGER =
Logger.getLogger(MyThread.class);
public void run() {
//perform some task
LOGGER.info("Hello from thread...");
}
}

Before Java 8, we only had this way to create a Runnable object. But since Java 8, we can create a Runnable object using a Lambda expression.

After creating the Runnable object, we need to pass it to a Thread constructor that receives a Runnable object as an argument:

Runnable runnable = () -> LOGGER.info("Hello from thread...");
Thread t = new Thread(runnable);

Some constructors don't take the Runnable object as an argument, such as Thread(). In that case, we need to take another approach in order to create a thread:

public class ThreadExample1 {
public static void main(String[] args) {
MyThread t = new MyThread1();
t.start();
}

}
class MyThread1 extends Thread {
private static final Logger LOGGER =
Logger.getLogger(MyThread1.class);
public void run() {
LOGGER.info("Hello from thread...");
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset