public class ThreadCommunication
{
public static void main ( String [ ] args )
{
sample sam = new sample ( );
OneThread one = new OneThread ( sam );
TwoThread two = new TwoThread ( sam );
one.start ( );
two.start ( );
}
}
class OneThread extends Thread
{
private sample sam;
public OneThread ( sample sam1 )
{
sam = sam1;
}
@Override
public void run ( )
{
sam.setNumber1 ( );
}
}
class TwoThread extends Thread
{
private sample sam;
public TwoThread ( sample sam1 )
{
sam = sam1;
}
@Override
public void run ( )
{
sam.setNumber2 ( );
}
}
class sample
{
private int number = 0;
public int getNumber ( )
{
return number;
}
public synchronized void setNumber1 ( )
{
for ( int i = 0 ; i < 10 ; i ++ )
{
if ( this.number != 1 )
{
this.number += 1;
System.out.println ( this.getNumber ( ) );
notify ( );
}
else
{
try
{
wait ( );
}
catch ( InterruptedException e )
{
e.printStackTrace ( );
}
}
}
}
public synchronized void setNumber2 ( )
{
for ( int i = 0 ; i < 10 ; i ++ )
{
if ( this.number == 1 )
{
this.number -= 1;
System.out.println ( this.getNumber ( ) );
notify ( );
}
else
{try
{
wait ( );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
}
}
}
}
雙進程操作一個對象的,wait,notify方法在synchronized塊來實現進程的喚醒和等待。
wait方法會釋放對象的鎖。