创建线程的4种方式是什么?

1 继承Thread类:本质实现了Runnable接口,调用start()方法开启新线程,并执行run()方法。

2 实现Runnable接口
3 使用Callable接口创建线程返回值
执行 Callable 任务后,可以获取一个 Future 的对象,在该对象上调用 get 就可以获取到 Callable 任务返回的 Object 了,再结合线程池接口 ExecutorService 就可以实现传说中有返回结果的多线程了。

public class TestCallable {
public static void main(String[] args) {
Thread1Demo td = new Thread1Demo();
//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask task = new FutureTask<>(td);
new Thread(task).start();
try {//2.接收线程运算后的结果
if (!task.isDone()) {
System.out.println(“task has not finished, please wait!”);
}
Integer sum = task.get(); //FutureTask 可用于 闭锁
System.out.println(“task return: -----” + sum);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class Thread1Demo implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100000; i++) { sum += i; }
return sum;
}
}

4 基于线程池的方式有返回值
不用每次都创建线程,使用Executor创建线程池,向其中加入任务。

public class ThreadPoolDemo {
public static void main(String[] args) {
//创建线程池
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
//向线程池提交任务
Future future = newCachedThreadPool.submit(new MyCallable());
if (!future.isDone()) {
System.out.println(“task has not finished, please wait!”);
}
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
} finally {
newCachedThreadPool.shutdown();
}
}
}
class MyCallable implements Callable {
@Override
public String call() throws Exception {
String value = “test”;
Thread.currentThread().sleep(5000);
return value;
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值