Stop a thread inside & outside the thread
程序员文章站
2022-03-02 10:48:36
...
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
public class AtomicDemo {
public static void main(String[] args) throws InterruptedException {
AtomicBoolean run = new AtomicBoolean(true);
Random rd = new Random();
System.out.println("This is the beginning of main thread.");
new Thread(() -> {
while (run.get()) {
int i = rd.nextInt(20);
System.out.println("i = " + i);
if (i >= 16) {
System.out.println("i >= 16, set run to false.");
run.set(false);
} else {
try {
System.out.println("Inner thread sleep 1 second.");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("run is set to false already.");
}).start();
Thread.sleep(10000);
run.set(false);
System.out.println("Main thread sleep for 10 seconds and set run to false.");
}
}
- If main thread already sleeps for 10 seconds, set
run
to false, inner thread stops. - If inner thread itself set
run
to false, inner thread stops.
转载于:https://www.jianshu.com/p/177aea9e0c6b
上一篇: 点到三角形的距离(三维)-使用Geometric Tools库
下一篇: 3、图层几何学
推荐阅读
-
[转]为什么 Thread.stop和Thread.suspend等被废弃了?
-
Thread stop
-
Thread.stop()为何废弃
-
Thread.stop()为何废弃
-
stop thread
-
thread stop() 方法为啥过期
-
How to Stop a Thread or a Task
-
Java Thread问题集之Thread.stop()篇
-
a thread named [Abandoned connection cleanup thread] but has failed to stop it
-
Stop a thread inside & outside the thread