We can create an instance of Runnable and pass it to Thread class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Runnable runnable = new Runnable() { | |
@Override | |
public void run() { | |
System.out.println("thread 1"); | |
} | |
}; | |
Thread thread1 = new Thread(runnable); | |
thread1.start(); |
Or we can override the run() method in the Thread class directly:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Thread thread2 = new Thread() { | |
@Override | |
public void run() { | |
System.out.println("thread 2"); | |
} | |
}; | |
thread2.start(); |
However the better solution (in most cases) is using the Executor interface.
It gives us a couple of benefits. In previous cases, if we want to start again the thread that has come to the terminated state we will get IllegalThreadStateException.
With Executor we can reuse the existing Runnable :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ExecutorService executor = Executors.newSingleThreadExecutor(); | |
Runnable runnable = new Runnable() { | |
@Override | |
public void run() { | |
System.out.println(Thread.currentThread().getName()); | |
} | |
}; | |
executor.execute(runnable); | |
// executing once again | |
executor.execute(runnable); | |
executor.shutdown(); |
What is even more important, it provides the ability to easily switch the implementation of running: using single thread, different kinds of thread pools or even scheduled periodic task.
We would just need to use different static factory method from Executors utility class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ExecutorService executor = Executors.newFixedThreadPool(2); | |
Runnable runnable = new Runnable() { | |
@Override | |
public void run() { | |
System.out.println(Thread.currentThread().getName()); | |
} | |
}; | |
executor.execute(runnable); | |
executor.execute(runnable); | |
executor.shutdown(); |
No comments:
Post a Comment