常见几种方式
- 继承 Thread 类
- 实现 Runnable/Callable 接口
- 线程池
Example
import java.util.concurrent.*;
public class TestThread {
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("继承 Thread 类");
}
}
static class MyRun implements Runnable{
@Override
public void run() {
System.out.println("实现 Runnable 接口");
}
}
static class MyCall implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("实现 Callable 接口");
return 1+2;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
new MyThread().start();
new Thread(new MyRun()).start();
FutureTask<Integer> futureTask = new FutureTask<>(new MyCall());
ExecutorService es = Executors.newCachedThreadPool();
es.submit(futureTask);
Integer result = futureTask.get();
System.out.println("result = " + result);
es.shutdown();
}
}