package concurrent;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @Auther:zhouhongliang
* @Date:2019/7/11
* @Description:
* Callable和Future一起使用
*/
public class CallableOne {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future zhangsan = executorService.submit(new MyCalllable("张三"));
Future lisi = executorService.submit(new MyCalllable("李四"));
Future wangwu = executorService.submit(new MyCalllable("王五"));
try {
//阻塞主线程 get()
System.out.println(zhangsan.get());
System.out.println(lisi.get());
//System.out.println(wangwu.get());
}catch (Exception e){
e.printStackTrace();
}
System.out.println("主线程执行完毕");
executorService.shutdown();
}
}
class MyCalllable implements Callable{
public MyCalllable(String name) {
this.name = name;
}
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public Object call() throws Exception {
Integer speed = new Random().nextInt(100);
Integer course = new Integer(0);
for (int i=1;i<=10;i++){
course = speed * i;
System.out.println(name + " 前进了"+course+"米,"+speed+"/秒");
if ("张三".equals(name)){
Thread.sleep(100);
}else{
Thread.sleep(500);
}
}
return course;
}
}
网站题目:JAVA多线程Callable和Future使用示例
文章源于:
http://chengdu.cdxwcx.cn/article/pjepoj.html