JavaSE小笔记--29(多线程3两个线程间的通信)

两个线程间的通信

什么时候需要通信?---多线程并发执行时,在默认情况下CPU时随机切换线程的,如果我们希望他们有规律的执行,就可以使用通信

如何实现通信?---如果希望线程等待--wait();如果希望唤醒等待的线程---notify()

------------------这两个方法必须在同步代码中执行,并且使用同步锁对象来调用


/*
 * 交替打印2行字符串
 */
public class Demo_07 {

	public static void main(String[] args) {
		final Printer p = new Printer();
		
		new Thread() {
			public void run(){
				while(true) {
					try {
						p.print1();
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			}
		}.start();
		
		new Thread() {
			public void run(){
				while(true) {
					try {
						p.print2();
					} catch (InterruptedException e) {
						
						e.printStackTrace();
					}
				}
			}
		}.start();

	}

}

class Printer{
	private int flag = 1;
	public void print1() throws InterruptedException {
		synchronized (this) {
			if(flag!=1) {
				this.wait();			//当前线程等待
			}
			System.out.print("学");
			System.out.print("习");
			System.out.println();
			flag = 2;
			this.notify();				//随机唤醒单个等待的线程,注意时随机
		}
	}
	public void print2() throws InterruptedException {
		synchronized (this) {
			if(flag!=2) {
				this.wait();
			}
			System.out.print("J");
			System.out.print("A");
			System.out.print("V");
			System.out.print("A");
			System.out.println();
			flag = 1;
			this.notify();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/xiaodunlp/article/details/80648474