简体   繁体   中英

Calling Thread doesn't stop after RejectedExecutionException

Why main thread is not stopped when one of the thread from threadpool throws RejectedExecutionException ?Am i doing something wrong here? 3rd thread in the threadpool is throwing RejectedExecutionException and i am not handling this exception in main thread. So do i necessarily handle this exception to make my main thread stop. Any help would be appreciated.

    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(1));
        threadPool.execute(new TestOne());
        threadPool.execute(new TestTwo());
        threadPool.execute(new TestThree());
        threadPool.shutdown();
        try {
            threadPool.awaitTermination(2L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("main thread stopped");
    }
}

class TestOne implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Executing task one");
            try {
                Thread.sleep(10);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

    }
}

class TestTwo implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Executing task two");
            try {
                Thread.sleep(10);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}

class TestThree implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Executing task three");
            try {
                Thread.sleep(10);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}

No threads from the thread pool are throwing a RejectedExecutionException . The main thread which is submitting the tasks to the thread pool is actually throwing the RejectedExecutionException .

The main thread will not block on submission as the spec's dictate it should not. There are mechanisms to do this, see ThreadPoolExecutor Block When Queue Is Full?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM