• Future方法详解


    future.get()和Future.get(long timeout, TimeUnit unit)

    package com.dwz.executors;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class FutureExample1 {
        
        private static void testGet() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<Integer> future = executorService.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 10;
            });
            //==========================================
            System.out.println("=========I will be printed quickly.==========");
            //==========================================
            
            Thread callerThread = Thread.currentThread();
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打断了callerThread和future.get()的阻塞,对线程池里面的线程没有影响,线程池里面的线程还在执行中
                callerThread.interrupt();
            }).start();
            
            Integer result = future.get();
            System.out.println(result);
        }
        
        private static void testGetWithTimeOut() throws InterruptedException, ExecutionException, TimeoutException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<Integer> future = executorService.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                    System.out.println("====== The time is longer than timeOut ========");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 10;
            });
            
            //该方法对调用着是超时退出的,对执行的线程没影响
            Integer result = future.get(5, TimeUnit.SECONDS);
            System.out.println(result);
        }
        
        public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
            testGet();
            testGetWithTimeOut();
        }
    }

    future.cancel(true)、future.isDone()和future.isCancelled()

    package com.dwz.executors;
    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ThreadFactory;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    public class FutureExample2 {
        
        private static void testIsDone1() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<Integer> future = executorService.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 10;
            });
            
            Integer result = future.get();
            System.out.println(result + " is done " + future.isDone());
        }
        
        private static void testIsDone2() {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<Integer> future = executorService.submit(() -> {
                throw new RuntimeException();
            });
            
            Integer result = null;
            try {
                result = future.get();
            } catch (Exception e) {
                System.out.println(result + " is done " + future.isDone());
            }
        }
        
        /**
         * try to cancel maybe failed
         * 1.task is completed already
         * 2.has already been canceled
         */
        private static void testCancel_1() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<Integer> future = executorService.submit(() -> 10);
            System.out.println(future.get());
            System.out.println(future.cancel(true));
        }
        
        private static void testCancel_2() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<Integer> future = executorService.submit(() -> {
                TimeUnit.SECONDS.sleep(10);
                return 10;
            });
            
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(future.cancel(true));
            System.out.println(future.cancel(true));
        }
        
        private static void testCancel_3() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            AtomicBoolean running = new AtomicBoolean(true);
            Future<Integer> future = executorService.submit(() -> {
                while(running.get()) {
                    
                }
                return 10;
            });
            
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(future.cancel(true));
            System.out.println(future.isDone());
            System.out.println(future.isCancelled());
        }
        
        private static void testCancel_4() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            AtomicBoolean running = new AtomicBoolean(true);
            Future<Integer> future = executorService.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                System.out.println("111111111111111111111");
                return 10;
            });
            
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(future.cancel(true));
            System.out.println(future.isDone());
            System.out.println(future.isCancelled());
        }
        
        //interrupted()与cancel配合使用
        private static void testCancel_5() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            AtomicBoolean running = new AtomicBoolean(true);
            Future<Integer> future = executorService.submit(() -> {
                while(!Thread.interrupted()) {
                    
                }
                System.out.println("111111111111111111111");
                return 10;
            });
            
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(future.cancel(true));
            System.out.println(future.isDone());
            System.out.println(future.isCancelled());
        }
        
        //暴力全部停止
        private static void testCancel_6() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
                
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setDaemon(true);
                    return thread;
                }
            });
            AtomicBoolean running = new AtomicBoolean(true);
            Future<Integer> future = executorService.submit(() -> {
                while(running.get()) {
                    
                }
                System.out.println("111111111111111111111");
                return 10;
            });
            
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(future.cancel(true));
            System.out.println(future.isDone());
            System.out.println(future.isCancelled());
        }
        
        private static void testCancel_7() throws InterruptedException, ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            AtomicBoolean running = new AtomicBoolean(true);
            Future<Integer> future = executorService.submit(() -> {
                while(!Thread.interrupted()) {
                    
                }
                System.out.println("111111111111111111111");
                return 10;
            });
            
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(future.cancel(true));
            System.out.println(future.isDone());
            System.out.println(future.isCancelled());
            TimeUnit.MILLISECONDS.sleep(10);
            //拿不到值
            System.out.println(future.get());
        }
        
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            testIsDone1();
            testIsDone2();
            testCancel_1();
            testCancel_2();
            testCancel_3();
            testCancel_4();
            testCancel_5();
            testCancel_6();
            testCancel_7();
        }
    }
  • 相关阅读:
    Groovy Simple file download from URL
    Connect to URL and dump webpage in Groovy Stack Overflow
    bash脚本测网络流量
    HTTPBuilder Overview
    nginx设置代理账号密码
    引爆流行
    RRDtool About RRDtool
    老王 python ,
    Ubuntu下安装GeoIP
    实时查看网络的流量
  • 原文地址:https://www.cnblogs.com/zheaven/p/13471046.html
Copyright © 2020-2023  润新知