Java多线程中的wait与notify

来源:互联网 发布:流水号生成算法 编辑:程序博客网 时间:2024/06/07 05:01
在Java多线程编程中,wait()的作用的是让当前线程进入阻塞状态,notify()是让当前线程唤醒继续执行。虽然是对线程状态的控制,但它们其实都是Object中的方法,这是因为wait与notify所起的作用与线程间的互斥锁有关。

在执行wait()和notify()之前,必须要先获得互斥锁,即一定要和synchronized一起使用。wait()的含义是让出获得的互斥锁,并让自己进入阻塞状态。在notify()的时候也已经获得了互斥锁,所做的事情就是唤醒当前线程继续执行。

假如synchronized的锁对象是obj的话,wait和notify正确的使用方法是obj.wait()和obj.notify()。如果使用this作为锁,则可以直接写成wait()和notify()。如果前后使用的锁对象不一致,会发生IllegalMonitorStateException

当有多个线程共同使用一个互斥锁时,notify()会随机选取一个执行过wait()的线程唤醒,其余会继续保持阻塞状态。如果想唤醒所有阻塞的进程,就使用到了notifyAll()。

下面的示例程序展示了wait()、notify()和notifyAll()的用法

public class WaitNotifyTest { public static void main(String[] args) { TestThread testThread1 = new TestThread(); TestThread testThread2 = new TestThread(); TestThread testThread3 = new TestThread(); testThread1.start(); testThread2.start(); testThread3.start(); try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { System.out.println("Main Thread Interrupted"); } System.out.println("Resume By Notify"); testThread1.resumeByNotify(); try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { System.out.println("Main Thread Interrupted"); } System.out.println("Resume By NotifyAll"); testThread1.resumeByNotifyAll(); }}class TestThread extends Thread { private static Object obj = new Object(); @Override public void run() { System.out.println(getName() + " Before Wait"); synchronized (obj) { try { obj.wait(); } catch (InterruptedException e) { System.out.println(getName() + " Test Thread Interrupted"); } } System.out.println(getName() + " After Wait"); } public void resumeByNotify() { synchronized (obj) { obj.notify(); } } public void resumeByNotifyAll() { synchronized (obj) { obj.notifyAll(); } } }

三个线程输出一段内容后通过wait()进入阻塞状态,随后通过调用所对象obj的notify()方法,使其中随机的一个线程唤醒,再通过notifyAll()使剩余的两个线程唤醒。

运行结果如下

Thread-0 Before WaitThread-1 Before WaitThread-2 Before WaitResume By NotifyThread-0 After WaitResume By NotifyAllThread-2 After WaitThread-1 After Wait

0 0
原创粉丝点击