Java 线程池
1.线程池
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(30, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(60), new ThreadPoolExecutor.AbortPolicy());
2.异步执行(主线程执行完了,子线程还没执行完)
public void testPool() throws InterruptedException { System.out.println("======start======="); for (int i = 0; i < 10; i++) { final int key = i; threadPoolExecutor.execute(() -> { test(key); }); } System.out.println("=========end========"); }
3.主线程等待子线程执行完
public void testPool() throws InterruptedException { System.out.println("======start======="); for (int i = 0; i < 10; i++) { final int key = i; threadPoolExecutor.execute(() -> { test(key); }); } threadPoolExecutor.shutdown(); System.out.println("=========end========"); }
4.执行带返回值的
public void testPool() throws InterruptedException, ExecutionException {
        System.out.println("======start=======");
        int result = 0;
        for (int i = 0; i < 10; i++) {
            final int key = i;
            Callable<Integer> callable = () -> test(key);
            Future<Integer> num = threadPoolExecutor.submit(callable);
            if (num.get() != null) {
                result = num.get();
            }
        }
        System.out.println("=====result====" + result);
        threadPoolExecutor.shutdown();
        System.out.println("=========end========");
    }
    private Integer test(int key) {
        System.out.println("=============" + key);
        if (key == 8) {
            System.out.println("====key===");
            return key;
        } else {
            return null;
        }
    }
                    
                
                
            
        
浙公网安备 33010602011771号