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