Java Reference
In-Depth Information
Create a class implementation that includes the task that needs to be run in a different
thread. Implement a Runnable interface in the task implementation class and start a
new Thread . In the following example, a counter is used to simulate activity, as a sep-
arate task is run in the background.
Note The code in this example could be refactored to utilize method references (see
Chapter 6 ) , rather than creating an inner class for the new Thread implementation.
However for clarity, the anonymous inner class has been shown.
private void someMethod() {
Thread backgroundThread = new Thread(new Runnable()
{
public void run() {
doSomethingInBackground();
}
},"Background Thread");
System.out.println("Start");
backgroundThread.start();
for (int i= 0;i < 10;i++) {
System.out.println(Thread.currentThread().getName()+":
is counting "+i);
}
System.out.println("Done");
}
private void doSomethingInBackground() {
System.out.println(Thread.currentThread().getName()+
": is Running in the background");
}
If the code is executed more than once, the output should be different from time to
time. The background thread will execute separately, so its message is printed at a dif-
ferent time across each run.
The same code for creating the background thread can be written as follows if
you're using lambda expressions:
Search WWH ::




Custom Search