wait和notify必须对同一对象操作才能够起到作用。
代码1:
- package waitnotify1;
- public class ThreadInstance implements Runnable{
- public void run() {
- double d = 0;
- synchronized(this){
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- for(int i = 0; i < 1000; i++){
- d += i;
- }
- System.out.println(d);
- notify();
- //假如还有一下sleep代码,那么即便是调用了notify,对方也不会立即从wait中回复,
- //因为该synchronized还没有运行完毕,毕竟它使用的还是wait调用的那个对象。
- /* try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }*/
- }
- }
- }
好了,我们对上面的例子进行一下测试:
- package waitnotify1;
- public class TestWaitNotify{
- public static void main(String[] args) {
- ThreadInstance ti = new ThreadInstance();
- Thread t = new Thread(ti);
- t.start();
- synchronized(t){
- try{
- System.out.println("等待中...");
- t.wait();
- System.out.println("它们运行完毕,不必等待了。");
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
我们运行上面的测试用例,得到一下测试结果:
---------------------------------------------------------------------------------------------------------------
等待中... (注意在此行打印完毕后并不是立刻打印下面的语句,而是等待用例程序中线程休眠时间结束会才打印)
499500.0
它们运行完毕,不必等待了。
---------------------------------------------------------------------------------------------------------------