📄 flagcomm.java
字号:
//: FlagComm.java
public class FlagComm {
public static void main(String[] args) {
FlagSend s = new FlagSend();
FlagRec r = new FlagRec(s);
Thread st = new Thread(s);
Thread rt = new Thread(r);
rt.setDaemon(true);
st.start();
rt.start();
try {
st.join(); // for Windows
while ( s.isValid ) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class FlagSend implements Runnable {
volatile int theValue;
volatile boolean isValid;
public void run() {
for ( int i=0; i<5; i++ ) {
while ( isValid ) {
Thread.yield();
}
theValue = (int)(Math.random()*256);
System.out.println("sending "+theValue);
isValid = true;
}
}
}
class FlagRec implements Runnable {
FlagSend theSender;
public FlagRec(FlagSend sender) {
theSender = sender;
}
public void run() {
while ( true ) {
while ( !theSender.isValid ) {
Thread.yield();
}
System.out.println("received "+theSender.theValue);
theSender.isValid = false;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -