Spa*_*tan 5 java multithreading synchronization volatile
此代码来自Effective Java(Item 66):(没有sync或volatile,这永远不会结束)
public class ThreadPractice {
static boolean canrunstatic;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!canrunstatic){i++;}
System.out.println("finished");
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
canrunstatic = true;
}
Run Code Online (Sandbox Code Playgroud)
正如布洛赫在该章中提到的那样,它永远不会在控制台上写"完成".我一直在玩这个类,并将该行添加到runnable run方法:
System.out.println("im still running");
Run Code Online (Sandbox Code Playgroud)
有了这个,while循环不仅增加i,而且在每个循环中打印出这个字符串.但是什么让我发疯,这样线程在1秒后停止,当主线程从睡眠状态恢复时.
修改:(停止没有volatile/sync)
public class ThreadPractice {
static boolean canrunstatic;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!canrunstatic){i++;System.out.println("im still running");}
System.out.println("finished");
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
canrunstatic = true;
}
Run Code Online (Sandbox Code Playgroud)
那么这背后的逻辑是什么?
| 归档时间: |
|
| 查看次数: |
247 次 |
| 最近记录: |