这里学习一下java多线程中的关于wait方法和notify方法的用法。
wait和notify方法的使用
一、wait与notify的简单实例
import java.util.concurrent.TimeUnit; public class WaitThreadTest { public static void main(String[] args) throws Exception { Object object = new Object(); new WaitThread(object).start(); TimeUnit.SECONDS.sleep(2); // 2秒之后唤醒 new NotifyThread(object).start(); } static class WaitThread extends Thread { private Object object; WaitThread(Object object) { this.object = object; } @Override public void run() { synchronized (object) { try { System.out.println("before wait."); object.wait(); System.out.println("after wait."); } catch (InterruptedException e) { e.printStackTrace(); } } } } static class NotifyThread extends Thread { private Object object; NotifyThread(Object object) { this.object = object; } @Override public void run() { synchronized (object) { System.out.println("before notify."); object.notify(); System.out.println("after notify."); } } } }
运行的结果如下:
before wait. before notify. after notify. after wait.
如果修改object.wait()为object.wait(1),运行的结果如下:
before wait. after wait. before notify. after notify.
友情链接
时间: 2024-11-14 06:48:41