JAVA基础 多线程-线程通信

  • 1.当input发现Resource中没有数据时,开始输入,输入完成后,叫output来输出。如果发现有数据,就wait();
    2.当output发现Resource中没有数据时,就wait() ;当发现有数据时,就输出,然后,叫醒input来输入数据。
package demo;

public class Test3 {
	/*
	 * 1.当input发现Resource中没有数据时,开始输入,输入完成后,叫output来输出。如果发现有数据,就wait();
	2.当output发现Resource中没有数据时,就wait() ;当发现有数据时,就输出,然后,叫醒input来输入数据。
	 * 
	 */
	public static void main(String[] args) {
		Resource r = new Resource();
		Input in = new Input(r);
		Output out = new Output(r);
		
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		
		t1.start();t2.start();
	}

}

class Output implements Runnable{
	private Resource r;
	public Output(Resource r) {
		this.r = r;
	}
	public void run() {
		synchronized (r) {
			while (true) {
				if(r.flag) {
					try {
						r.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.println(r.name + ":" + r.gender);
				r.flag = true;
				r.notify();
			}
		}
		
	}
	
	
}



class Input implements Runnable{
	private Resource r;
	public Input(Resource r) {
		this.r = r;
	}
	@Override
	public void run() {
		int x = 0;
		while(true) {
			synchronized (r) {
				if(!r.flag) {//检查flag 是否可以写入,不可写入暂停线程
					try {
						r.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				if(x%2==0) {//轮换着负值
					r.name = "小明";
					r.gender = "男";
				}else {
					r.name = "hanmeimei";
					r.gender = "nv";
				}
				//写完数据更改flag
				r.flag = false;
				//唤醒线程
				r.notify();
				
			}
			x++;
			
		}


		
		
	}
	
}


class Resource{
	
	public String name;
	public String gender;
	public boolean flag = true;
	
//	public Resource(String name, String gender) {
//		this.name = name;
//		this.gender = gender;
//	}

}





猜你喜欢

转载自blog.csdn.net/alexzt/article/details/80194542