1、说明

对象调用notify()方法后, 调用后虚拟机可选择任何一个调用了 该对象wait()的线程投入运行,选择顺序不由代码控制,由虚拟机实现。如果是notifyAll(),则唤醒所有等待的线程运行。

值得注意的是,对象调用notify()方法后,本线程还可以继续执行。notify()或者notifyAll()方法并不是真正释放锁,必须等到synchronized方法或者语法块执行完才真正释放锁。

 

 

2、使用例子程序进行说明

 

import java.util.Vector;

public class ThreadWaitNotifyTest {

    public static void main( String args[] ) {
        Vector < String > obj = new Vector < String >();
        Thread consumer = new Thread( new Consumer( obj ) );
        Thread producter = new Thread( new Producter( obj ) );
        consumer.start();
        producter.start();
    }
}

/* 消费者 */
class Consumer implements Runnable {
    private Vector < String > obj;

    public Consumer( Vector < String > v ) {
        this.obj = v;
    }

    public void run() {
        synchronized ( obj ) {
            while ( true ) {
                try {
                    if ( obj.size() == 0 ) {
                        obj.wait();
                    }
                    System.out.println( "Consumer:goods have been taken" );
                    System.out.println( "obj size: " + obj.size() );
                    obj.clear();
                    obj.notify();
                }
                catch ( Exception e ) {
                    e.printStackTrace();
                }
            }
        }
    }
}

/* 生产者 */
class Producter implements Runnable {
    private Vector < String > obj;

    public Producter( Vector < String > v ) {
        this.obj = v;
    }

    public void run() {
        synchronized ( obj ) {
            while ( true ) {
                try {
                    if ( obj.size() != 0 ) {
                        obj.wait();
                    }

                    obj.add( new String( "apples" ) );
                    obj.notify();
                    System.out.println( "Producter:obj are ready" );
                    Thread.sleep( 500 );
                }
                catch ( Exception e ) {
                    e.printStackTrace();
                }
            }
        }
    }

}


3、程序运行结果

 

 

Producter:obj are ready
Consumer:goods have been taken
obj size: 1
Producter:obj are ready
Consumer:goods have been taken
obj size: 1
Producter:obj are ready
Consumer:goods have been taken
obj size: 1
Producter:obj are ready
Consumer:goods have been taken
obj size: 1

 

 

 

 

 

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐