1.Java创建线程的三种方式
package file;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author XiangYida
* @version 2019/4/6 9:58
*/
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
new Thread1().start();
new Thread(new Thread2()).start();
FutureTask<String> futureTask = new FutureTask(new Thread3());
new Thread(futureTask).start();
String result = futureTask.get();
System.out.println(result);
}
}
class Thread1 extends Thread {
@Override
public void run() {
System.out.println("I am thread 1");
}
}
class Thread2 implements Runnable {
@Override
public void run() {
System.out.println("I am thread 2");
}
}
class Thread3 implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("I am thread 3");
return "thread3'return ";
}
}
2.结果
I am thread 1
I am thread 2
I am thread 3
thread3'return
3.总结
-
使用继承方式的好处是方便传参,你可以在子类里面添加成员变量,通过set方法设置参数或者通过构造函数进行传递。
-
使用Runnable 方式,则只能使用主线程里面被声明为final 的变量。Runable解决了不能多继承的限制。
-
前两种方式都没办法拿到任务的返回结果,但是Futuretask 方式可以。
本文介绍了Java中创建线程的三种主要方式:通过继承Thread类、实现Runnable接口及使用Callable与FutureTask。每种方式都有其适用场景,如解决多继承限制、方便传参或获取任务返回结果。

397

被折叠的 条评论
为什么被折叠?



