1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class thread3 { public static void main(String args[]) throws ExecutionException, InterruptedException { ExecutorService executorService= Executors.newFixedThreadPool(2); Runner3 xiaoMing=new Runner3(); xiaoMing.setName("小明"); Runner3 xiaoHing=new Runner3(); xiaoHing.setName("小红");
Future<Integer> result1=executorService.submit(xiaoMing); Future<Integer> result2=executorService.submit(xiaoHing); try { Thread.sleep(5000); }catch (Exception e){
} executorService.shutdown(); System.out.println("小明"+result2.get()); System.out.println("小红"+result1.get()); }
} class Runner3 implements Callable<Integer>{ private String name; public void setName(String name){ this.name=name; } @Override public Integer call() throws Exception { Integer speed=new Random().nextInt(100); Integer distince=0; for(int i=1;i<=100;i++){ Thread.sleep(10); distince=speed*i; System.out.println(name+"前进"+speed*i); } return distince; } }
|