这段代码有几个问题:

  1. 在主线程中使用了CounterApp.join(),但是CounterApp是一个类,不是一个线程对象,应该使用Counter.join()

  2. SleepyCounter线程中,当调用SleepyCounter.interrupt()时,会中断SleepyCounter线程。但是在循环中使用Thread.currentThread().interrupted()来判断线程是否被中断是不正确的。应该使用Thread.interrupted()来判断线程是否被中断。

  3. SleepyCounter线程中,当线程被中断时,应该立即停止循环并退出线程。

以下是修改后的代码:

public class CounterApp {
    public static void main(String[] args) throws InterruptedException {
        Thread Counter = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=10; i<=500; i++){
                    System.out.println(i);
                }
            }
        });
        Counter.start();
        Thread SleepyCounter = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 10; i <= 500; i++) {
                    System.out.print(i);
                    if(Thread.interrupted()){
                        System.out.print(' The thread is interrupted
');
                        return;
                    }
                }
            }
        });
        SleepyCounter.start();
        SleepyCounter.interrupt();
        System.out.println("Finished");
        Counter.join();
    }
}
Java 多线程编程:线程中断的正确使用 - CounterApp 代码分析与优化

原文地址: https://www.cveoy.top/t/topic/pjEW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录