⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 waitcomm.java

📁 讲解在java平台上用AWT编写与图形有关的小程序
💻 JAVA
字号:
//: WaitComm.java

public class WaitComm {
	public static void main(String[] args) {
		WFlagSend s = new WFlagSend();
		WFlagRec r = new WFlagRec(s);
		Thread st = new Thread(s);
		Thread rt = new Thread(r);
		rt.setDaemon(true);
		st.start();
		rt.start();
		try {
			st.join();
			while ( s.isValid ) {
				Thread.sleep(100);
			}
		} catch ( InterruptedException e ) {
			e.printStackTrace();
		}
	}
}

class WFlagSend implements Runnable {
	int theValue;
	boolean isValid;
	
	public void run() {
		for ( int i=0; i<5; i++ ) {
			synchronized(this) {
				while ( isValid ) {
					try {
						this.wait();
					} catch ( InterruptedException e ) {
						e.printStackTrace();
					}
				}
			}
			theValue = (int)(Math.random()*256);
			System.out.println("sending "+theValue);
			synchronized(this) {
				isValid = true;
				this.notify();
			}
		}
	}
}

class WFlagRec implements Runnable {
	WFlagSend theSender;
	
	public WFlagRec(WFlagSend sender) {
		theSender = sender;
	}
	
	public void run() {
		while ( true ) {
			synchronized(theSender) {
				while ( !theSender.isValid ) {
					try {
						theSender.wait();
					} catch ( InterruptedException e ) {
						e.printStackTrace();
					}
				}
			}
			System.out.println("received "+theSender.theValue);
			synchronized(theSender) {
				theSender.isValid = false;
				theSender.notify();
			}
		}
	}
}
		
		

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -