flagcomm.java
来自「讲解在java平台上用AWT编写与图形有关的小程序」· Java 代码 · 共 55 行
JAVA
55 行
//: 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 + =
减小字号Ctrl + -
显示快捷键?