java 中 wait和notify的用法

package com.test;


public class OutputThread  {

    public  static  Object lockObj=new Object();
  public  static  void  main(String [] args){

      ThreadA t1 = new ThreadA("t1");

      synchronized(OutputThread.lockObj) {
          try {
              // 启动“线程t1”
              System.out.println(Thread.currentThread().getName()+" start t1");
              t1.start();

              // 主线程等待,t1线程获取到锁开始执行
              System.out.println(Thread.currentThread().getName()+" wait()");
              OutputThread.lockObj.wait(); //等待的是当前线程

              System.out.println(Thread.currentThread().getName()+" continue");
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }


  }

}

class ThreadA extends Thread{

    public ThreadA(String name) {
        super(name);
    }

    public void run() {
        synchronized (OutputThread.lockObj) {
            System.out.println(Thread.currentThread().getName()+" call notify()");
            // 唤醒当前的wait线程
            OutputThread.lockObj.notify();
        }
    }
}

 

posted @ 2018-01-11 14:23  甜菜波波  阅读(552)  评论(0编辑  收藏  举报