Runable与Callable
1 package com.enterec.orders.web; 2 3 import lombok.SneakyThrows; 4 5 import java.util.ArrayList; 6 import java.util.List; 7 import java.util.concurrent.*; 8 9 /** 10 * @Description TODO 11 * @ClassName MyThread 12 * @Author LuoLT 13 * @Date 2020-10-12 14 **/ 15 public class MyThread { 16 public static void main(String[] args) throws ExecutionException, InterruptedException { 17 //创建一个线程池 18 int poolSize = 3; 19 Long beginTime = System.currentTimeMillis(); 20 ExecutorService pool = Executors.newFixedThreadPool(poolSize); 21 List<Future> futures = new ArrayList<>(); 22 for (int i = 0; i < poolSize; i++) { 23 MyCallable myThread = new MyCallable("my rallable test------" + i); 24 // 执行任务并获取Future对象 25 Future f = pool.submit(myThread); 26 // pool.execute(myThread);//执行任务,无返回值 27 futures.add(f); 28 System.out.println(i); 29 } 30 // 关闭线程池 31 pool.shutdown(); 32 for (Future f : futures) { 33 System.out.println("res: " + f.get().toString());//get()阻塞至返回结果 34 } 35 System.out.println("cast:" + (System.currentTimeMillis() - beginTime) / 1000); 36 // Callable myCallable = new MyCallable("my callable test"); 37 // FutureTask<String> task = new FutureTask<>(myCallable);//执行单线程带返回结果时 FutureTask 38 // Long beginTime = System.currentTimeMillis(); 39 // Thread cthread = new Thread(task); 40 // cthread.start(); 41 // String result = task.get();//get()阻塞至返回结果 42 // Long endTime = System.currentTimeMillis(); 43 // System.out.println("hello," + result); 44 // System.out.println("cast:" + (endTime - beginTime) / 1000); 45 46 } 47 } 48 49 class MyCallable implements Callable<String> { 50 private String str; 51 52 public MyCallable(String str) { 53 this.str = str; 54 } 55 56 @Override 57 public String call() throws Exception { 58 Thread.sleep(10000); 59 return this.str + " append some chars and return it"; 60 } 61 } 62 63 class MyRunable implements Runnable { 64 private String str; 65 66 public MyRunable(String str) { 67 this.str = str; 68 } 69 70 @SneakyThrows 71 @Override 72 public void run() { 73 Thread.sleep(10000); 74 System.out.println(this.str + " append some chars and return it"); 75 } 76 }
0
1
2
res: my rallable test------0 append some chars and return it
res: my rallable test------1 append some chars and return it
res: my rallable test------2 append some chars and return it
cast:10
Process finished with exit code 0

浙公网安备 33010602011771号