//to thread joint way!!!!!
Import the Java. Util. *;
The class RWthread
{
Public static void main (String args [])
{
String readName="reader", writeName="writer threads";
ReadWrite rw=new ReadWrite (readName writeName);
Thread the read and write;
Read=new Thread (rw);
Write=new Thread (rw);
Read the elegantly-named setName (readName);
Write the elegantly-named setName (writeName);
Read. Start ();
Write. Start ();
}
}
The class ReadWrite implements Runnable
{
String ID=null;
String name=null;
String readName writeName;
A Boolean flag=false;
Public ReadWrite (String s1, String s)
{
ReadName=s1;
WriteName=s;
}
Public void the run ()
{
ReadOrWrite ();
}
Public synchronized void readOrWrite ()//synchronization method
{
If (Thread. CurrentThread (). The getName () equals (readName))
{
Scanner reader=new Scanner (System. In);
While (true)
{
If (flag)
{
Try {
Wait ();
} catch InterruptedException (e) {}
}
System. The out. Println (" please enter the student number: ");
ID=reader. NextLine ();
If (ID. Equals (" finish "))
{
System. Out.println (" \ n read threads and write thread end work!" );
Flag=true;
Notify ();
Reader. The close ();
return;
}
System. The out. Println (" please input your name: ");
Name=reader. NextLine ();
Flag=true;
Notify ();
}
}
Else if (Thread. CurrentThread (). The getName () equals (writeName))
{
While (true)
{
if(! Flag)
{
Try {
Wait ();
} catch InterruptedException (e) {}
}
If (ID. Equals (" finish "))
return;
System. The out. Println (" \ n output student ID: "+ ID +", the output name: "+ name);
System.out.println();
Flag=false;
Notify ();
}
}
}
}