Java Reference
In-Depth Information
Using a Method Reference
From Java 8, you can use the method reference of a method of any class that takes no parameters and returns void
as the code to be executed by a thread. The following code declares a ThreadTest class that contains an execute()
method. The method contains the code to be executed in a thread.
public class ThreadTest {
public static void execute() {
System.out.println("Hello Java thread!");
}
}
The following snippet of code uses the method reference of the execute() method of the ThreadTest class to
create a Runnable object:
Thread myThread = new Thread(ThreadTest::execute);
myThread.start();
The thread will execute the code contained in the execute() method of the ThreadTest class.
A Quick Example
Let's look at a simple example to print integers from 1 to 500 in a new thread. Listing 6-2 lists the code for the
PrinterThread class that performs the job. When the class is run, it prints integers from 1 to 500 on the standard output.
Listing 6-2. Printing Integers from 1 to 500 in a New Thread
// PrinterThread.java
package com.jdojo.threads;
public class PrinterThread {
public static void main(String[] args) {
// Create a Thread object
Thread t = new Thread(PrinterThread::print);
// Start the thread
t.start();
}
public static void print() {
for (int i = 1; i <= 500; i++) {
System.out.print(i + " ");
}
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... 497 498 499 500
I used a method reference to create the thread object in the example. You can use any of the other ways discussed
earlier to create a thread object.
 
Search WWH ::




Custom Search