gpt4 book ai didi

java - 使用 volatile 或原子 boolean 值停止可运行线程的问题

转载 作者:行者123 更新时间:2023-11-30 08:18:51 26 4
gpt4 key购买 nike

我试图使用 volatile 变量或原子变量来停止正在运行的线程。但我对此有一些疑问。下面是我尝试过的代码。

public class DemoThread {
class DemoRunnable implements Runnable {

private String name;

public volatile boolean isRunning = true;

public DemoRunnable() {
}

public DemoRunnable(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public synchronized boolean isRunning() {
return isRunning;
}

public synchronized void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}

@Override
public void run() {

System.out.println(" runnable ..." + name + " isRunning "
+ isRunning);

while (isRunning) {
int i;
for (i = 0; i < 100; i++) {
System.out.println("--------------------> i " + i
+ " name " + name + " isRunning " + isRunning);
}
// if (i > 0) {
// System.out.println(" volatile not working ");
// throw new RuntimeException("volatile not working " + name);
// }
}
System.out.println(" run method ends ..." + isRunning);
}

}

private void demoStop(int count) {
DemoRunnable runnable1 = new DemoRunnable("" + count);

Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable1);

t1.start();
t2.start();

runnable1.isRunning = false;
// runnable1.setRunning(false);

}

public static void main(String[] args) {
DemoThread demoThread = new DemoThread();

for (int i = 0; i < 200; i++) {
try {
demoThread.demoStop(i);
} catch (Exception e) {
e.printStackTrace();
}
}

}

}

在执行上面的代码时,有时包含while循环的run方法会被执行多次。一旦 isStopped 设置为 false,有什么方法可以停止 while 循环的运行吗?

线程的中断方法不会停止正在运行的方法。

我尝试了原子 boolean 值和 isStop 变量的同步方法,但结果是相同的。

最佳答案

如果您的可运行检查被中断,interrupt() 将按预期停止读取。

    @Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
someTask();
// thread can sleep if you like, add this block
try {
Thread.sleep(10);
} catch (InterruptedException e) {
log.warn("Interrupted", e);
break;
}
}
}

您的嵌套循环不会检查原子 boolean 值,自然不会停止。无论如何,interrupt() 比蹩脚的 boolean 标志要好得多。有关更多详细信息,请参阅 ExecutorService 和 Future。

关于java - 使用 volatile 或原子 boolean 值停止可运行线程的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29264216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com