1. 程式人生 > >java非同步呼叫

java非同步呼叫

連線:https://www.cnblogs.com/dennyzhangdd/p/7010972.html
public class AsyncDemo {
    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Test1 t1 = new Test1();
        FutureTask<Integer> ft1 = new FutureTask<>(t1);
        executorService.submit(ft1);
        //會阻塞主執行緒
//System.out.println("r1 = " +ft1.get()); //jdk1.8的實現方式 Test3 test3 = new Test3(); CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(test3, executorService); //採用lambada的實現方式,不會阻塞主執行緒 future1.thenAccept(e -> System.out.println(e + " ok")); System.out
.println("main thread is running"); //System.out.println("r1 = " +ft1.get()); Test2 t2 = new Test2(); FutureTask<Integer> ft2 = new FutureTask<>(t2); executorService.submit(ft2); System.out.println("r2 = " +ft2.get()); executorService.shutdown(); } } class
Test1 implements Callable<Integer>{ @Override public Integer call() throws Exception { Integer i = new Integer(1000); System.out.println("sleep before i = "+i); Thread.sleep(5000); i = i + 5000; System.out.println("sleep after i = "+i); return i; } } class Test2 implements Callable<Integer>{ @Override public Integer call() throws Exception { Integer i = new Integer(2000); System.out.println("sleep before i2 = "+i); i = i + 5000; System.out.println("sleep after i2 = "+i); return i; } } class Test3 implements Supplier<Integer>{ @Override public Integer get() { Integer i = new Integer(3000); System.out.println("sleep before i3 = "+i); try { Thread.sleep(8000); } catch (InterruptedException e) { e.printStackTrace(); } i = i + 8000; System.out.println("sleep after i3 = "+i); return i; } }