繁体   English   中英

两个线程使用相同的变量

[英]Two threads using same variable

private void stopThread() {
    thread1.canRun(false);
}

private void createThread() {
    thread1.stopThread();
    thread1.canRun(true);
    thread1 = new Thread(thread1);
    t.start();

}

我只有一个按钮。 当我单击按钮时,我执行的线程数将为n,而当我再次单击按钮时,最后一个线程应停止并创建一个新线程。

问题是当我创建第二个线程时,似乎最后一个并没有停止并且都继续运行

  @Override
    public void run() {
    try {
        for (int i = 0; i <= TimeOut && canRun; i++) {
             System.out.println(i);
            Thread.sleep(1000);

            }

        }

    private volatile boolean canRun;

问题可能出在以下几行:

thread1.stopThread();    // <-- sets canRun to false
thread1.canRun(true);    // <-- sets canRun to back to true

您还可以使用true初始化canRun ,这意味着线程可以在其初始状态下运行:

 private volatile boolean canRun = true;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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