线程池的简单运用Executors.newFixedThreadPool

/**
 * https://blog.csdn.net/weixin_40271838/article/details/79998327
 *
 * 通过运行结果,可以看到我们创建了一个固定数量为2的FixedThreadPool,所以第3个任务会进入等待队列,因为核心线程不够用了,而当有任务经过6s的时间执行完后,有了空闲线程,那么第3个任务就可以接着执行了
 */
public class TestMain {
    //格式化
    static SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //AtomicInteger用来计数
    static AtomicInteger number = new AtomicInteger();
 
    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("运行第" + number.incrementAndGet() + "个线程,当前时间【" + sim.format(new Date()) + "】");
                    try {
                        Thread.sleep(6000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
 
        //写法二
        ExecutorService executorService2 = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 3; i++) {
            executorService2.execute(()->{
                System.out.println("运行第" + number.incrementAndGet() + "个线程,当前时间【" + sim.format(new Date()) + "】");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
 
 
        //写法三
        ExecutorService executorService3 = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 3; i++) {
            executorService.submit(()->{
                System.out.println("运行第" + number.incrementAndGet() + "个线程,当前时间【" + sim.format(new Date()) + "】");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

原文链接:https://blog.csdn.net/u011441473/article/details/117450881

你可能感兴趣的:(线程池的简单运用Executors.newFixedThreadPool)