处理从Java中的线程中断



我有以下代码来创建多个线程。

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

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

在下面的工作对您有效(Interrupt((调用是不需要的,添加了流动性(。我还建议研究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);
} 

最新更新