/*
Multithreading: a producer a consumer
*/
Class Resource
{
private String name;
private int age;
Boolean flag=false;
Public synchronized void Setresource (String name,int count) throws Interruptedexception
{
while (flag)
This.wait ();
{this.wait (); this.notify (); System.out.println ("producer while Continue");}
This.name=name+count;
System.out.println ("producer" +this.name+ "...");
Flag=true;
This.notify ();
}
Public synchronized String GetName () throws Interruptedexception
{
while (!flag)
This.wait ();
{this.wait (); this.notify (); SYSTEM.OUT.PRINTLN ("Consumer while Continue");}
Flag=false;
This.notify ();
return this.name;
}
}
Class Producerthread implements Runnable
{
int count=1;
Public Resource r=new Resource ();
Public Resource GetResource ()
{
return R;
}
public void Run ()
{
while (true)
{
Try{r.setresource ("Zhang San", Count);} catch (Interruptedexception ex) {}
count++;
}
}
}
Class Sellerthread implements Runnable
{
Private Resource R;
int count=20;
Public Sellerthread (Resource R)
{
This.r=r;
}
public void Run ()
{
while (true)
TRY{SYSTEM.OUT.PRINTLN ("Consumer" +r.getname () + "...");} catch (Interruptedexception ex) {}
}
}
Class Oneproducersellerthread
{
public static void Main (string[] args) throws Interruptedexception
{
Producerthread pt=new Producerthread ();
Sellerthread st=new Sellerthread ();
New Thread (PT). Start ();
New Thread (New Sellerthread (Pt.getresource ())). Start ();
}
}
Problems with multithreading (a consumer of a producer)