A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 李厚斌 中级黑马   /  2014-4-6 21:16  /  536 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Tset

  2. {

  3.     public static void main(String[] args) throws InterruptedException

  4.     {  
  5.             ThreadB b=new ThreadB();

  6.             b.start();

  7.       System.out.println("b is start....");

  8.       synchronized(b)

  9.       {
  10.             System.out.println("Waiting for b to complete...");
  11.             b.wait();
  12.             System.out.println("Completed.Now back to main thread");

  13.       }

  14.       System.out.println("Total is :"+b.total);

  15.      }

  16. }

  17. class ThreadB extends Thread

  18. {

  19.     int total;

  20.     public void run()

  21.     {

  22.       synchronized(this)

  23.       {

  24.         System.out.println("ThreadB is running..");

  25.         for (int i=0;i<5;i++ )

  26.         {
  27.           total +=i;
  28.           System.out.println("total is "+total);
  29.         }
  30.         notify();
  31.       }

  32.     }

  33. }
复制代码
运行结果怎么会出现

b is start....
ThreadB is running..
total is 0
total is 1
total is 3
total is 6
total is 10
Waiting for b to complete...

然后主线程无法获得锁 一直等待。。

正常情况不是应该主线程wait 然后睡眠,等线程B执行完之后 notify,主线程再执行吗?

您需要登录后才可以回帖 登录 | 加入黑马