import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author Chris Wu
* @date 2020/5/9 9:49
*/
public class ThreeThreadMethod {
//继承Thread
//优点:可以在方法中通过this调用Thread的方法
//缺点:可拓展性差,因为java是单继承的
static class Thread1 extends Thread {
@Override
public void run() {
System.out.println("继承Thread类");
//可以直接通过this调用Thread的方法
this.isInterrupted();
}
}
//实现Runnable接口
//优点:有很好的拓展性
//缺点:无法通过this调用Thread的方法,必须先获取当前线程Thread.currentThread()
static class Thread2 implements Runnable {
public void run() {
System.out.println("实现Runnable接口");
//无法直接通过this调用Thread的方法
Thread.currentThread().isInterrupted();
}
}
//实现callable接口,泛型为返回值的类型
//可以取得返回值的Runnable
static class Thread3 implements Callable<String> {
public String call() throws Exception {
System.out.println("实现Callable接口");
//无法直接通过this调用Thread的方法
Thread.currentThread().isInterrupted();
return "implements Callable";
}
}
public static void main(String[] args) {
//使用继承了Thread类的类来启动线程
Thread1 thread1 = new Thread1();
thread1.start();
//使用实现Runnable接口的类来启动线程
Thread2 thread2 = new Thread2();
new Thread(thread2).start();
//使用实现Callable接口的类来启动线程
Thread3 thread3 = new Thread3();
//由于Thread接受实现runnable接口的类,所以要把实现Callable接口的类进行包装,FutureTask实现Runnable接口
FutureTask<String> futureTask = new FutureTask<String>(thread3);
new Thread(futureTask).start();
try {
//通过FutureTask的get方法可以拿到线程操作结果的返回值,get是一个阻塞方法
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
【P说】Java三种启动线程的方法
最新推荐文章于 2022-11-12 12:15:33 发布