最简实例说明wait、notify、notifyAll的使用方法

wait()、notify()、notifyAll()是三个定义在Object类里的方法,可以用来控制线程的状态。

这三个方法最终调用的都是jvm级的native方法。随着jvm运行平台的不同可能有些许差异。



•如果对象调用了wait方法就会使持有该对象的线程把该对象的控制权交出去,然后处于等待状态。
•如果对象调用了notify方法就会通知某个正在等待这个对象的控制权的线程可以继续运行。
•如果对象调用了notifyAll方法就会通知所有等待这个对象控制权的线程继续运行。


其中wait方法有三个over load方法:

wait()

wait(long)

wait(long,int)

wait方法通过参数可以指定等待的时长。如果没有指定参数,默认一直等待直到被通知。





以下是一个演示代码,以最简洁的方式说明复杂的问题:

简要说明下:

NotifyThread是用来模拟3秒钟后通知其他等待状态的线程的线程类;

WaitThread是用来模拟等待的线程类;

等待的中间对象是flag,一个String对象;

main方法中同时启动一个Notify线程和三个wait线程;





Java代码 
1.public class NotifyTest {  
2.    private  String flag = "true";  
3. 
4.    class NotifyThread extends Thread{  
5.        public NotifyThread(String name) {  
6.            super(name);  
7.        }  
8.        public void run() {       
9.            try {  
10.                sleep(3000);//推迟3秒钟通知  
11.            } catch (InterruptedException e) {  
12.                e.printStackTrace();  
13.            }  
14.              
15.                flag = "false";  
16.                flag.notify();  
17.        }  
18.    };  
19. 
20.    class WaitThread extends Thread {  
21.        public WaitThread(String name) {  
22.            super(name);  
23.        }  
24. 
25.        public void run() {  
26.              
27.                while (flag!="false") {  
28.                    System.out.println(getName() + " begin waiting!");  
29.                    long waitTime = System.currentTimeMillis();  
30.                    try {  
31.                        flag.wait();  
32.                    } catch (InterruptedException e) {  
33.                        e.printStackTrace();  
34.                    }  
35.                    waitTime = System.currentTimeMillis() - waitTime;  
36.                    System.out.println("wait time :"+waitTime);  
37.                }  
38.                System.out.println(getName() + " end waiting!");  
39.              
40.        }  
41.    }  
42. 
43.    public static void main(String[] args) throws InterruptedException {  
44.        System.out.println("Main Thread Run!");  
45.        NotifyTest test = new NotifyTest();  
46.        NotifyThread notifyThread =test.new NotifyThread("notify01");  
47.        WaitThread waitThread01 = test.new WaitThread("waiter01");  
48.        WaitThread waitThread02 = test.new WaitThread("waiter02");  
49.        WaitThread waitThread03 = test.new WaitThread("waiter03");  
50.        notifyThread.start();  
51.        waitThread01.start();  
52.        waitThread02.start();  
53.        waitThread03.start();  
54.    }  
55. 
56.} 
public class NotifyTest {
private  String flag = "true";

class NotifyThread extends Thread{
public NotifyThread(String name) {
super(name);
}
public void run() {
try {
sleep(3000);//推迟3秒钟通知
} catch (InterruptedException e) {
e.printStackTrace();
}

flag = "false";
flag.notify();
}
};

class WaitThread extends Thread {
public WaitThread(String name) {
super(name);
}

public void run() {

while (flag!="false") {
System.out.println(getName() + " begin waiting!");
long waitTime = System.currentTimeMillis();
try {
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
waitTime = System.currentTimeMillis() - waitTime;
System.out.println("wait time :"+waitTime);
}
System.out.println(getName() + " end waiting!");

}
}

public static void main(String[] args) throws InterruptedException {
System.out.println("Main Thread Run!");
NotifyTest test = new NotifyTest();
NotifyThread notifyThread =test.new NotifyThread("notify01");
WaitThread waitThread01 = test.new WaitThread("waiter01");
WaitThread waitThread02 = test.new WaitThread("waiter02");
WaitThread waitThread03 = test.new WaitThread("waiter03");
notifyThread.start();
waitThread01.start();
waitThread02.start();
waitThread03.start();
}

}

OK,如果你拿这段程序去运行下的话, 会发现根本运行不了,what happened?满屏的java.lang.IllegalMonitorStateException。

没错,这段程序有很多问题,我们一个个来看。



首先,这儿要非常注意的几个事实是



1.任何一个时刻,对象的控制权(monitor)只能被一个线程拥有。
2.无论是执行对象的wait、notify还是notifyAll方法,必须保证当前运行的线程取得了该对象的控制权(monitor)
3.如果在没有控制权的线程里执行对象的以上三种方法,就会报java.lang.IllegalMonitorStateException异常。
4.JVM基于多线程,默认情况下不能保证运行时线程的时序性


基于以上几点事实,我们需要确保让线程拥有对象的控制权。

也就是说在waitThread中执行wait方法时,要保证waitThread对flag有控制权;

在notifyThread中执行notify方法时,要保证notifyThread对flag有控制权。



线程取得控制权的方法有三:



1.执行对象的某个同步实例方法。
2.执行对象对应类的同步静态方法。
3.执行对该对象加同步锁的同步块。
我们用第三种方法来做说明:
将以上notify和wait方法包在同步块中

Java代码 
1.synchronized (flag) {  
2.                flag = "false";  
3.                flag.notify();  
4.            } 
synchronized (flag) {
flag = "false";
flag.notify();
}



Java代码 
1.synchronized (flag) {  
2.                while (flag!="false") {  
3.                    System.out.println(getName() + " begin waiting!");  
4.                    long waitTime = System.currentTimeMillis();  
5.                    try {  
6.                        flag.wait();  
7.                    } catch (InterruptedException e) {  
8.                        e.printStackTrace();  
9.                    }  
10.                    waitTime = System.currentTimeMillis() - waitTime;  
11.                    System.out.println("wait time :"+waitTime);  
12.                }  
13.                System.out.println(getName() + " end waiting!");  
14.            } 
synchronized (flag) {
while (flag!="false") {
System.out.println(getName() + " begin waiting!");
long waitTime = System.currentTimeMillis();
try {
flag.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
waitTime = System.currentTimeMillis() - waitTime;
System.out.println("wait time :"+waitTime);
}
System.out.println(getName() + " end waiting!");
}

我们向前进了一步。

问题解决了吗?

好像运行还是报错java.lang.IllegalMonitorStateException。what happened?



这时的异常是由于在针对flag对象同步块中,更改了flag对象的状态所导致的。如下:

flag="false";

flag.notify();

对在同步块中对flag进行了赋值操作,使得flag引用的对象改变,这时候再调用notify方法时,因为没有控制权所以抛出异常。



我们可以改进一下,将flag改成一个JavaBean,然后更改它的属性不会影响到flag的引用。

我们这里改成数组来试试,也可以达到同样的效果:





Java代码 
1.private   String flag[] = {"true"}; 
private   String flag[] = {"true"};



Java代码 
1.synchronized (flag) {  
2.            flag[0] = "false";  
3.            flag.notify();  
4.        } 
synchronized (flag) {
flag[0] = "false";
flag.notify();
}



Java代码 
1.synchronized (flag) {  
2.                while (flag[0]!="false") {  
3.                    System.out.println(getName() + " begin waiting!");  
4.                    long waitTime = System.currentTimeMillis();  
5.                    try {  
6.                        flag.wait();  
7.                          
8.                    } catch (InterruptedException e) {  
9.                        e.printStackTrace();  
10.                    } 
synchronized (flag) {
while (flag[0]!="false") {
System.out.println(getName() + " begin waiting!");
long waitTime = System.currentTimeMillis();
try {
flag.wait();

} catch (InterruptedException e) {
e.printStackTrace();
}



这时候再运行,不再报异常,但是线程没有结束是吧,没错,还有线程堵塞,处于wait状态。



原因很简单,我们有三个wait线程,只有一个notify线程,notify线程运行notify方法的时候,是随机通知一个正在等待的线程,所以,现在应该还有两个线程在waiting。



我们只需要将NotifyThread线程类中的flag.notify()方法改成notifyAll()就可以了。notifyAll方法会通知所有正在等待对象控制权的线程。



最终完成版如下:





Java代码 
1.public class NotifyTest {  
2.    private String flag[] = { "true" };  
3. 
4.    class NotifyThread extends Thread {  
5.        public NotifyThread(String name) {  
6.            super(name);  
7.        }  
8. 
9.        public void run() {  
10.            try {  
11.                sleep(3000);  
12.            } catch (InterruptedException e) {  
13.                e.printStackTrace();  
14.            }  
15.            synchronized (flag) {  
16.                flag[0] = "false";  
17.                flag.notifyAll();  
18.            }  
19.        }  
20.    };  
21. 
22.    class WaitThread extends Thread {  
23.        public WaitThread(String name) {  
24.            super(name);  
25.        }  
26. 
27.        public void run() {  
28.            synchronized (flag) {  
29.                while (flag[0] != "false") {  
30.                    System.out.println(getName() + " begin waiting!");  
31.                    long waitTime = System.currentTimeMillis();  
32.                    try {  
33.                        flag.wait();  
34. 
35.                    } catch (InterruptedException e) {  
36.                        e.printStackTrace();  
37.                    }  
38.                    waitTime = System.currentTimeMillis() - waitTime;  
39.                    System.out.println("wait time :" + waitTime);  
40.                }  
41.                System.out.println(getName() + " end waiting!");  
42.            }  
43.        }  
44.    }  
45. 
46.    public static void main(String[] args) throws InterruptedException {  
47.        System.out.println("Main Thread Run!");  
48.        NotifyTest test = new NotifyTest();  
49.        NotifyThread notifyThread = test.new NotifyThread("notify01");  
50.        WaitThread waitThread01 = test.new WaitThread("waiter01");  
51.        WaitThread waitThread02 = test.new WaitThread("waiter02");  
52.        WaitThread waitThread03 = test.new WaitThread("waiter03");  
53.        notifyThread.start();  
54.        waitThread01.start();  
55.        waitThread02.start();  
56.        waitThread03.start();  
57.    }  
58. 
59.} 

猜你喜欢

转载自88543006.iteye.com/blog/2234212
今日推荐