生产者和消费者同步线程

public class HoldIntegerSynchronized 
{
	private int sharedInt=-1;
	private boolean writeable=true;
	
	public synchronized void setSharedInt(int val)
	{
		while(!writeable)
		{
			try
			{
				wait();
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		
		System.err.println(Thread.currentThread().getName()+
		                   "setting sharedInt to"+val);
		sharedInt=val;
		writeable=false;
		notify();
	}
	
	public synchronized int getSharedInt()
	{
		while(writeable)
		{
			try
			{
				wait();
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		
		writeable=true;
		notify();
		
		System.err.println(Thread.currentThread().getName()+
		                   "retrieving sharedInt value"+sharedInt);
		return sharedInt;
	}
}
 public class ConsumeInteger extends Thread { private HoldIntegerSynchronized cHold; public ConsumeInteger(HoldIntegerSynchronized h) { super("ConsumeInteger"); cHold=h; } public void run() { int val,sum=0; do { try { Thread.sleep((int)(Math.random()*10000)); } catch(InterruptedException e) { System.err.println(e.toString()); } val=cHold.getSharedInt(); sum+=val; }while(val!=10); System.err.println(getName()+"retrieved values totaling:"+ sum+"\nTerminating "+getName()); } }

 

 

public class ProduceInteger extends Thread
{
	private HoldIntegerSynchronized pHold;
	
	public ProduceInteger(HoldIntegerSynchronized h)
	{
		super("ProduceInteger");
		pHold=h;
	}
	
	public void run()
	{
		for(int count=1;count<=10;count++)
		{
			try
			{
				Thread.sleep((int)(Math.random()*10000));
			}
			catch(InterruptedException e)
			{
				System.err.println(e.toString());
			}
			
			pHold.setSharedInt(count);
		}
		
		System.err.println(getName()+"finished producing values"+
		                   "\nTermininating "+getName());
	}
}

 

 

public class SharedCell 
{
	public static void main(String[] args)
	{
		HoldIntegerSynchronized h=new HoldIntegerSynchronized();
		ProduceInteger p=new ProduceInteger(h);
		ConsumeInteger c=new ConsumeInteger(h);
		
		p.start();
		c.start();
	}	
}

 

 

你可能感兴趣的:(thread,C++,c,C#)