Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用相同变量的两个线程_Java_Multithreading_Synchronization - Fatal编程技术网

Java 使用相同变量的两个线程

Java 使用相同变量的两个线程,java,multithreading,synchronization,Java,Multithreading,Synchronization,我只有一个按钮。 当我点击按钮时,我执行计数为n的线程 当我再次单击按钮时,最后一个线程应该停止并创建一个新线程 问题是,当我创建第二个线程时,最后一个线程似乎没有停止,并且两个线程都保持运行 private void stopThread() { thread1.canRun(false); } private void createThread() { thread1.stopThread(); thread1.canRun(true); thread1 =

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

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

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

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

}

问题可能出在以下几行:

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

            }

        }

    private volatile boolean canRun;

从您的代码摘录来看,您的canRuntrue似乎设置了thread1.stopThread。所以你可以试着去掉这条线。
thread1.stopThread();    // <-- sets canRun to false
thread1.canRun(true);    // <-- sets canRun to back to true
 private volatile boolean canRun = true;