wait方法是让当前线程等待,这里的当前线程不是指t,而是主线程。 wait会释放锁,等到其他线程调用notify方法时再继续运行。
可以看下面的例子。

11 package com.citi.test.mutiplethread.demo0503; 2 2 3 3 import java.util.Date; 4 4 5 5 public class WaitTest { 6 6 public static void main(String[] args) { 7 7 ThreadA t1=new ThreadA("t1"); 8 8 System.out.println("t1:"+t1); 9 9 synchronized (t1) { 1010 try { 1111 //启动线程 1212 System.out.println(Thread.currentThread().getName()+" start t1"); 1313 t1.start(); 1414 //主线程等待t1通过notify唤醒。 1515 System.out.println(Thread.currentThread().getName()+" wait()"+ new Date()); 1616 t1.wait();// 不是使t1线程等待,而是当前执行wait的线程等待 1717 System.out.println(Thread.currentThread().getName()+" continue"+ new Date()); 1818 } catch (Exception e) { 1919 e.printStackTrace(); 2020 } 2121 } 2222 } 2323 } 2424 2525 class ThreadA extends Thread{ 2626 public ThreadA(String name) { 2727 super(name); 2828 } 2929 @Override 3030 public void run() { 3131 synchronized (this) { 3232 System.out.println("this:"+this); 3333 try { 3434 Thread.sleep(2000);//使当前线程阻塞1秒 3535 } catch (InterruptedException e) { 3636 // TODO Auto-generated catch block 3737 e.printStackTrace(); 3838 } 3939 System.out.println(Thread.currentThread().getName()+" call notify()"); 4040 this.notify(); 4141 } 4242 } 4343 }

下面是执行结果。

可以看到synchronized(this),和synchronized(t1), 锁的是同一个对象。
这个程序有两个线程,一个是主线程main,一个是线程t1,所以会有锁的竞争,因为是main方法先运行到第9行,所以先获取到锁。
这样就导致了32行到40行的代码必须在main主线程释放锁的时候才运行,而t1.await()就释放了锁,所以我们看执行结果。
32行在15行之后执行。
17行会等待t1线程执行完毕调用notify之后再执行。
这里就说明了,
在代码中t1.await(),是让运行这行代码的线程等待,而不是让t1这个线程等待。