java - 线程无法停止

标签 java multithreading

为什么我的帖子停不下来???

 class Threadz {

    class runP implements Runnable {
        int num;
        private volatile boolean exit = false;
        Thread t;
        public runP() {
            t = new Thread(this, "T1");
            t.start();
        }

        @Override
        public void run() {
            while(!exit) {
                System.out.println(t.currentThread().getName()+": "+num);
                num++;  
                try {
                    t.sleep(200);   
                } catch(InterruptedException e) {}
            }
        }
        public void stop() {
            exit = true;
        }
    }

    public static void main(String[] a) {
        runP rp = new Threadz().new runP();
        if(rp.num == 1) {rp.stop();}
    }

}

如果我使用 rp.num == 0,线程可以立即停止。但是,为什么当我更改 rp.num == x(x 是任何大于 0 的数字)时线程无法停止?请帮我解决这个问题...感谢您的帮助。

最佳答案

因为这段代码不是在线程的run()方法中执行的:

    runP rp = new Threadz().new runP();
    if (rp.num == 1) {
        rp.stop();
    }

它与 0 一起工作,因为 int 的默认值为 0。 但它不一定在应用程序的所有执行中都是正确的,因为 runP 的线程可以运行并在检查之前递增 num :if (rp.num == 0)

在runP线程的run方法中移动停止条件:

@Override
public void run() {
    while(!exit) {
        System.out.println(t.currentThread().getName()+": "+num);
        num++;  
        try {
            t.sleep(200);   
        } catch(InterruptedException e) {}

        if (rp.num == 1) {
          exit = true;
        }
    }
}

关于java - 线程无法停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41699287/

相关文章:

java - 运行 3 个线程并在 Java 中等待

multithreading - coldfusion 11后台处理程序和cfmail线程

java - 在 Java 中使用“=?”比较两个值

java - 依赖注入(inject)框架的基础

java - 无法通过 UDP protobuf 将大于 127 的整数值从 C++ 发送到 Java

c++ - tbb::concurrent_queue 容器中的 std::deque 是否等效?

java - 在 Spring MVC 中流式传输 JSON 输出

JavaFX : Is it possible to use variable resolution in "fx:define"

c++ - C++ 中的列表不为空,但没有要迭代的元素

c++ - boost thread_group 将 unique_ptr 的所有权移动到线程