Java基礎之雙進程通信

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方法會釋放對象的鎖。





發佈了34 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章