黑马程序员技术交流社区

标题: notify()唤醒线程后接着代码块执行 [打印本页]

作者: Shey    时间: 2015-3-16 15:30
标题: notify()唤醒线程后接着代码块执行

先放上代码:
  1. package temp;

  2. class NotifyDemoTest implements Runnable {

  3.         public boolean flag = true;

  4.         @Override
  5.         public void run() {
  6.                 synchronized (this) {
  7.                         System.out.println("A");
  8.                         if (flag)
  9.                                 try {
  10.                                         flag = false;
  11.                                         this.wait();
  12.                                 } catch (Exception e) {
  13.                                 }
  14.                         else {
  15.                                 flag = true;
  16.                                 this.notify();
  17.                         }
  18.                         System.out.println("B");
  19.                 }
  20.         }
  21. }

  22. public class NotifyDemo {
  23.         public static void main(String[] args) {
  24.                 NotifyDemoTest ndt = new NotifyDemoTest();
  25.                 new Thread(ndt).start();
  26.                 new Thread(ndt).start();
  27.         }
  28. }
  29. 结果:
  30. A
  31. A
  32. B
  33. B
复制代码

就不用我多说了吧,notify唤醒线程后,线程接着原来代码执行到的地方继续执行,不会重新开始
csdn同步








欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2