JAVA多線程Callable和Future使用示例

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; } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章