import java.util.concurrent.atomic.AtomicInteger;
public class VolatilePattern1 extends Thread{
volatile boolean shutdownRequested;
private AtomicInteger count = new AtomicInteger();
public void shutdown() {
shutdownRequested = true;
}
public void run() {
System.out.println("Thread:" + Thread.currentThread().getName()+" started.");
while (!shutdownRequested) {
System.out.println("working ..."+count);
count.getAndIncrement();
try {
Thread.sleep(50);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Thread:" + Thread.currentThread().getName()+" started.");
VolatilePattern1 vp = new VolatilePattern1();
vp.start();
try {
Thread.sleep(2000);
} catch(InterruptedException ie) {
ie.printStackTrace();
} finally {
vp.shutdown();
}
}
}
加不加Volatile看不出有啥效果啊?
最新推荐文章于 2024-06-21 11:17:26 发布
本文介绍了一个使用Java volatile关键字实现线程间通信的例子。通过一个简单的循环任务,展示如何利用volatile变量来通知工作线程停止运行。同时引入了AtomicInteger进行线程安全的计数。
15万+

被折叠的 条评论
为什么被折叠?



