您好,登錄后才能下訂單哦!
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;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。