通过ExecuteService,Callable,Future实现带有返回值的多线程:
1、通过实现Callable接口创建线程类
package com.example.demo.morethread;
import java.util.concurrent.*;
/**
*使用带有返回值的线程
*/
public class CallableDemo implements Callable<String> {
private String str;
public CallableDemo(String str){
this.str=str;
}
@Override
public String call() throws Exception {
if("线程1".equals(str)){
Thread.sleep(1000);
}
System.out.println("线程:"+str);
return str;
}
}
2、测试:
package com.example.demo.morethread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService= Executors.newFixedThreadPool(10);
CallableDemo callableDemo=new CallableDemo("线程1");
CallableDemo callableDemo1=new CallableDemo("线程2");
Future<String> future=executorService.submit(callableDemo);
Future<String> future1=executorService.submit(callableDemo1);
System.out.println(future.get());//阻塞,线程1的值返回之后才会继续向下执行
System.out.println(future1.get());//阻塞
executorService.shutdown();
}
}
运行结果如下: