Wait
-
java的wait()方法是让当前线程等待,当前线程不是指t而是指主线程(让执行wait的线程等待)
-
wait会释放锁,等待其他线程调用notify/notifyAll()再继续运行
package com.citi.test.mutiplethread.demo0503; 2 3 import java.util.Date; 4 5 public class WaitTest { 6 public static void main(String[] args) { 7 ThreadA t1=new ThreadA("t1"); 8 System.out.println("t1:"+t1); 9 synchronized (t1) { 10 try { 11 //启动线程 12 System.out.println(Thread.currentThread().getName()+" start t1"); 13 t1.start(); 14 //主线程等待t1通过notify唤醒。 15 System.out.println(Thread.currentThread().getName()+" wait()"+ new Date()); 16 t1.wait();// 不是使t1线程等待,而是当前执行wait的线程等待 17 System.out.println(Thread.currentThread().getName()+" continue"+ new Date()); 18 } catch (Exception e) { 19 e.printStackTrace(); 20 } 21 } 22 } 23 } 24 25 class ThreadA extends Thread{ 26 public ThreadA(String name) { 27 super(name); 28 } 29 @Override 30 public void run() { 31 synchronized (this) { 32 System.out.println("this:"+this); 33 try { 34 Thread.sleep(2000);//使当前线程阻塞1秒 35 } catch (InterruptedException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } 39 System.out.println(Thread.currentThread().getName()+" call notify()"); 40 this.notify(); 41 } 42 } 43 }
Join
- join方法的原理就是调用相应线程的wait方法进行等待操作的,例如A线程中调用了B线程的join方法,则相当于在A线程中调用了B线程的wait方法,当B线程执行完(或者到达等待时间),B线程会自动调用自身的notifyAll方法唤醒A线程,从而达到同步的目的