Mark Knowledge of Java Thread (2): Notify and Wait

Don’t Ask Until I Call You

When I was a child, there was a grocery which was stocked many items I might buy with my friends. Every day I hoped to find originality items in it so I asked the buyer with the same question “Are there any new things ?” The buyer was so tired to reply each people that he put a white board in front of his grocery and write some items information.

Wait a Moment Because Trust

Wait method is in class Object, it means all objects can invoke this method. It causes the current thread to wait until either another thread invokes notify method.

public final native void wait(long timeout) throws InterruptedException;

Can I do that?

public class ThreadTest {

    public static void main(String[] args) throws InterruptedException{
        System.out.println("Not get object monit to invoke wait method.");
        ThreadTest t= new ThreadTest();
        t.wait();
    }
}

Of cource not.

result:
Not get object monit to invoke wait method.
Exception in thread "main" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:502)
    at ThreadTest.main(ThreadTest.java:7)

Remember that wait method must get object own monitor. We should invoke it in synchronized method or block as below.


public class ThreadTest {

    public static void main(String[] args) throws InterruptedException{
        System.out.println("Get object monit by synchronized.");
        ThreadTest t= new ThreadTest();
        synchronized(t){
            t.wait();           
        }
    }
}

result:
Get object monit by synchronized.

Notify Only You Because Promise

Somebody wants me, I will call him even after a long time. As the same as method wait notify method is in object class, too. Of cource ,when it is invoked it should get object monitor first.

 public final native void notify();

A Wonderful Story

Now return my child story. The buyer notifies me and my friends to buy some items.

Created with Raphaël 2.1.0 Main Thread Main Thread Buyer Buyer Boy A Boy A Boy B Boy B create buyer create boy A create boy B wait new items come stock surprise Hey hurry up! Hey hurry up! Buy! No enough money!

public class ThreadTest {

    public static void main(String[] args) throws InterruptedException{

        final Object item = new Object();

        Thread buyer=new Thread(){

            public void run() {
                System.out.println("Buyer:I am buyer.");
                System.out.println("Buyer:After 5 seconds,I will stock items");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(item){
                    System.out.println("Buyer:I have stocked items");
                    item.notifyAll();
                }
            }

        };

        Thread boyA = new Thread(){
            public void run() {
                System.out.println("Boy A:I am boy A.");
                synchronized(item){
                    try {
                        System.out.println("Boy A:I am waitting for item.");
                        item.wait();
                        System.out.println("Boy A:Great it is what I want.");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }


        };

        Thread boyB = new Thread(){
            public void run() {
                System.out.println("Boy B:I am boy B.");
                synchronized(item){
                    try {
                        System.out.println("Boy B:I am waitting for item.");
                        item.wait();
                        System.out.println("Boy B:What a shame, I have no enough money.");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }


        };

        buyer.start();
        boyB.start();
        boyA.start();
        try {
            Thread.sleep(10000);
            System.out.println("finish story.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值