synchronized2:生产者与消费者的同步

由生产者Provider提供Info,然后Consumer取走,保证数据为最新生产的,且生产者线程与消费者线程保持同步。

class Info{
	private String name;
	private String content;
	private boolean flag = true;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getContent() {
		return content;
	}
	/**
	 * @see 第一次,flag=true,consumer线程等待,provider线程的set()方法执行到super.notify(),将consumer线程唤醒,同时将flag=false,provider线程进入wait状态;
	 * @see consumer线程唤醒后输出内容,并将flag=true,consumer线程进入wait状态,同时唤醒provider线程;
	 * @see 第二次,如同第一次,以此类推
	 */
	public void setContent(String content) {
			this.content = content;
	}
	public synchronized void set(String name,String content){
		if(!flag){
			try{
				super.wait() ;
			}catch(InterruptedException e){
				e.printStackTrace() ;
			}
		}
		this.setName(name) ;
		try{
			Thread.sleep(300) ;
		}catch(InterruptedException e){
			e.printStackTrace() ;
		}
		this.setContent(content) ;
		flag  = false ;	
		super.notify() ;
	}
	public synchronized void get(){
		if(flag){
			try{
				super.wait() ;
			}catch(InterruptedException e){
				e.printStackTrace() ;
			}
		}
		try{
			Thread.sleep(300) ;
		}catch(InterruptedException e){
			e.printStackTrace() ;
		}
		System.out.println(this.getName() + " --> " + this.getContent()) ;
		flag  = true ;
		super.notify() ;
	}
}

class Provider implements Runnable{
	private Info info;
	boolean flag = false;
	public Provider(Info info){
		this.info = info;
	}
	@Override
	public void run() {
		for(int i=0;i<50;i++){
				try {
					Thread.sleep(60);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(flag){
					this.info.set("王一洋","程序员");
					flag=false;
				}else{
					this.info.set("java","gis");
					flag=true;
				}
			}
		}
}

class Consumer implements Runnable{
	private Info info;
	public Consumer(Info info){
		this.info = info;
	}
	@Override
	public void run() {
		for(int i=0;i<50;i++){
				try {
					Thread.sleep(70);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				info.get();
		}
	}
}

public class ThreadCaseDemo2 {
	public static void main(String[] args) {
		Info info = new Info();
		Provider pr = new Provider(info);
		Thread t1 = new Thread(pr,"provider");
		Consumer co = new Consumer(info);
		Thread t2 = new Thread(co,"consumer");
		t1.start();
		t2.start();
	}
}


运行结果:

ava --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis
王一洋 --> 程序员
java --> gis


 

你可能感兴趣的:(多线程)