callable + 线程池的方式 卖飞机票或火车票


import java.util.concurrent.*;

public class LeetCode {

    /**
     * 飞机票默认张数
     */
    private static int ticket = 1;

    public static void main(String args[]) {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 8,
                1000, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.AbortPolicy());

        Callable<String> stringCallable = new Callable<String>() {
            @Override
            public synchronized String call() {
                /**
                 * 卖100张
                 */
                while (ticket <= 100) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "窗口在卖第:" + ticket++ + "张飞机票!");
                        wait(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return "3";
            }
        };
        for (int i = 1; i <= 20; i++) {
            threadPoolExecutor.submit(new FutureTask<>(stringCallable));
        }
    }
}

上一篇:Java并发——Callable和Future接口,java基础题目编程题


下一篇:有余额2000,两个线程每次取200(Callable)