java wait()方法和notify()方法的使用

1、说明

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

值得注意的是,对象调用notify()方法后,本线程还可以继续执行。


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

package com.zte.ums.zenap.pm.analysis;

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



你可能感兴趣的:(java,多线程)