你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

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

2021/12/19 17:01:23

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));
        }
    }
}