处理Java中的线程中断

时间:2019-05-07 20:33:43

标签: java multithreading

我具有以下用于创建多个线程的代码。

    AtomicBoolean shutdown = new AtomicBoolean(false);
    List<Thread> threadList = new ArrayList<>();
    for (int i = 0; i < POOL_SIZE; i++) {
        Thread thread = new Thread(() -> {
            while (!shutdown.get()) {
                try {
                    factory.get().run();
                } catch (Exception e) {
                    log.error("Exception occurred in the thread execution ", e);
                }
            }
        });
        thread.start();
        threadList.add(thread);
    }

现在,我想做的是当发生任何中断时,我想将shutdown变量的值更改为true,这样它将杀死所有线程。如何在此代码中添加这样的处理程序?

1 个答案:

答案 0 :(得分:0)

下面的事情对您有用吗(不需要中断()调用,为流程可见而添加)。我还建议您研究java ExecutorService的实现,而不是生成线程。

AtomicBoolean shutdown = new AtomicBoolean(false);
for (int i = 0; i < POOL_SIZE; i++) {
    Thread thread = new Thread(() -> {
        do {
            try {
                System.out.println("sleep for 5s");
                Thread.sleep(10000);
                if(Thread.currentThread().getName().equalsIgnoreCase("Thread8")){
                    throw new InterruptedException();
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName()+" interrupted. Setting shutdown to true");
                shutdown.set(true);
            }

            if(shutdown.get()){
                System.out.println("Found shutdown instruction..exiting loop for "+Thread.currentThread().getName());
                Thread.currentThread().interrupt();
            }
        } while (!shutdown.get());
    });
    thread.start();
    thread.setName("Thread"+i);
}