线程通信
作者:
徐振杰 | 来源:发表于
2018-12-18 14:38 被阅读0次
- synchronized:线程A等待线程B于是就实现了通信
- while轮询:这样会导致cpu的使用率较低,而且有内存可见性问题。因为线程每次都是去读本地线程栈的信息,因此如果别的线程改变了它也察觉不到。
public class ee {
public static class RunThread extends Thread {
volatile private boolean isRunning = true; // 加了volatile才具有可见性
public boolean isRunning() {
return isRunning;
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
@Override
public void run() {
System.out.println("进入到run方法中了");
while (isRunning == true) {
}
System.out.println("线程执行完成了");
}
}
public static void main(String[] args) {
try {
RunThread thread = new RunThread();
thread.start();
Thread.sleep(1000);
thread.setRunning(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- wait/notify
- 管道机制,前面三种都是共享内存机制,管道应该是消息同行机制
线程通信
本文标题:线程通信
本文链接:https://www.haomeiwen.com/subject/qkflkqtx.html
网友评论