Three ways to use threads
Three ways to use threads
- Implement the Runnable interface
- Implement the Callable interface
- Inherit the Thread class
Implementing the Runnable interface and the Callable interface is equivalent to creating a task that can run in a thread; after the task is created, it needs to be driven by Thread.
Runnable
Need to implement run() in the interface, write the tasks to be executed in the method
/**
* @Auther: match
* @Date: 2021/2/20 16:25
* @Description: 演示Runnable接口的简单使用
*/
public class RunnableDemo {
private static class Task implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Thread thread = new Thread(new Task() );
thread.start();
}
}
Callable interface
Callable can have a return value, and the return value is encapsulated by FutureTask.
/**
* @Auther: match
* @Date: 2021/2/20 16:31
* @Description: 演示Callable接口的简单使用
*/
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1.创建callable的实现类
CallableTask callableTask = new CallableTask();
//2. 创建一个任务
FutureTask futureTask = new FutureTask<>(callableTask);
// 交友线程执行
Thread thread = new Thread(futureTask);
thread.start();
//通过get方法得到返回值
System.out.println(futureTask.get());
}
static class CallableTask implements Callable{
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
return "这是Callable的返回值";
}
}
}
Inherit Thread
/**
* @Auther: match
* @Date: 2021/2/20 16:37
* @Description: 演示Thread的简单使用
*/
public class ThreadDemo extends Thread {
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
}
}
Comparison of three ways
The way to implement the interface is better because:
- Java does not support multiple inheritance systems, but multiple interfaces can be implemented, so if you inherit the Thread class, you cannot inherit other classes.
- The class can only be executable, and it is too expensive to inherit the entire Thread class.