Java creates threads in three ways
There are three main ways to create threads in Java:
1. Inherit the Thread class
2. Implement the Runnable interface
3. Use Callable and Future
1. Inherit Thead class to create thread
(1) Inherit Thread class and rewrite run method
(2) Create thread object
(3) Call the start() method of the thread object to start the thread
public class CreateThreadTest {
public static void main(String[] args) {
new ThreadTest().start();
newThreadTest().start(); }}class ThreadTest extends Thread{
private int i = 0;
@Override
public void run(a) {
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " is running: "+ i); }}}Copy the code
2. Implement the Runnable interface to create threads
(1) Define a class that implements the Runnable interface and override its run() method
(2) Create an object of the Runnable implementation class as the target parameter for creating the Thread object, which is the real Thread object
(3) Call the start() method of the thread object to start the thread
public class CreateThreadTest {
public static void main(String[] args) {
RunnableTest runnableTest = new RunnableTest();
new Thread(runnableTest, Thread 1 "").start();
new Thread(runnableTest, Thread 2 "").start(); }}class RunnableTest implements Runnable{
private int i = 0;
@Override
public void run(a) {
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " is running: "+ i); }}}Copy the code
3. Create threads using Callable and Future
Unlike the Runnable interface, the Callable interface provides a call() method as the thread body. The Call () method is more powerful than the run() method: The call() method can have a return value and can declare to throw an exception.
public interface Callable<V> {
V call(a) throws Exception;
}
Copy the code
Java5 provides the Future interface to receive the return value of the Call () method in the Callable interface. The Callable interface is a new Java5 interface and is not a subinterface of the Runnable interface. Therefore, Callable objects cannot be directly used as the target of Thread objects. To address this problem, the RunnableFuture interface is introduced. The RunnableFuture interface is a subinterface of the Runnable interface and the Future interface, and can be used as the target of Thread objects. At the same time, Java5 provides an implementation class for the RunnableFuture interface: FutureTask, which can act as a target for Thread objects.
(1) Define a class that implements the Callable interface and overwrites the Call () method, which will act as the thread body and return a value
(2) Create an instance of the Callable implementation class and use the FutureTask class to wrap the Callable object
(3) Use FutureTask as the target of Thread object to create and start the Thread
(4) Call FutureTask’s get() method to get the return value after the execution of the child thread
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CreateThreadTest {
public static void main(String[] args) {
CallableTest callableTest = new CallableTest();
FutureTask<Integer> futureTask = new FutureTask<>(callableTest);
new Thread(futureTask).start();
try {
System.out.println("Return value of child thread:" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch(ExecutionException e) { e.printStackTrace(); }}}class CallableTest implements Callable{
@Override
public Integer call(a) throws Exception {
int sum = 0;
for (int i = 1; i < 101; i++) {
sum += i;
}
System.out.println(Thread.currentThread().getName() + " is running: " + sum);
returnsum; }}Copy the code
Comparison of three ways to create threads
1. Advantages of implementing Runnable/Callable interfaces over inheriting Thread classes
(1) Suitable for multiple threads to share resources
(2) The restriction of single inheritance in Java can be avoided
(3) Increase the robustness of the program, code and data independence
(4) Thread pools can only be placed into Runable or Callable interface implementation classes, not directly into the classes that inherit Thread
2. Difference between Callable and Runnable
(1) Callable overrides the call() method, Runnable overrides the run() method
(2) The call() method can return a value after execution, but the run() method does not return a value
(3) The call() method can throw an exception, but the run() method cannot
(4) Run the Callable task to get a Future object, which represents the result of the asynchronous calculation. By using the Future object, you can know the execution status of the task, cancel the execution of the task, and obtain the execution result
Reference:
Three ways to create threads in Java and their comparison
Java creates threads in three main ways