线程分配不足会导致什么问题

啥也不说,直接上代码

package offer_0831;

import java.util.concurrent.*;

public class ThreadOverFlow {

    public static void main(String[] args) {
        ExecutorService es = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(1));
        final CountDownLatch cdl = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            final int finalID = i+1;
            es.submit(new Runnable() {
                public void run() {
                    System.out.println("t num is " + finalID);
                    try {
                        Thread.sleep(finalID*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("stop t and num is " + finalID);
                    cdl.countDown();
                }
            });
        }

        System.out.println("ok ,good bye");
    }
}

执行结果

Connected to the target VM, address: '127.0.0.1:6218', transport: 'socket'
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3d8c7aca rejected from java.util.concurrent.ThreadPoolExecutor@668bc3d5[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
	at offer_0831.ThreadOverFlow.main(ThreadOverFlow.java:12)
t num is 0
t num is 1
stop t and num is 0
t num is 2
stop t and num is 1
stop t and num is 2

结论:

线程池拒绝接收线程提交

你可能感兴趣的:(Java,自修-进阶,线程,分配不足,线程池,提交线程)