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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© pphdsny3 高级黑马   /  2012-12-19 11:14  /  1150 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test {

  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {

  6. Waiting w=new Waiting();
  7. new Thread (w) .start();
  8. new Thread (w) .start();
  9. }

  10. }

  11. class Waiting implements Runnable {
  12. boolean flag = false;

  13. public synchronized void run() {
  14. if (flag) {
  15. flag = false;
  16. System.out.print("1");
  17. try {
  18. this.wait();
  19. } catch (Exception e) {
  20. }
  21. System.out.print("2");
  22. } else {
  23. flag = true;
  24. System.out.print("3");
  25. try {
  26. Thread.sleep(2000);
  27. } catch (Exception e) {
  28. }
  29. System.out.print("4");
  30. notifyAll();
  31. }
  32. }
  33. }
复制代码
疑问:这段代码的输出结果是什么?这段代码会运行结束么?

评分

参与人数 1技术分 +1 收起 理由
刘芮铭 + 1

查看全部评分

6 个回复

倒序浏览
输出结果是314,可以运行结束~~先出现3,然后出现41
回复 使用道具 举报
运行结果
很明显,代码最后输出了System.out.print("1"); 这一句,然后进行了
try {
this.wait();
}
即等待状态,而且没有唤醒其他的线程,因此就一直等待。

评分

参与人数 1技术分 +1 收起 理由
刘芮铭 + 1

查看全部评分

回复 使用道具 举报
孙辉辉 发表于 2012-12-19 11:34
运行结果
很明显,代码最后输出了System.out.print("1"); 这一句,然后进行了
try {

notifyAll()不会唤醒那个等待的线程么?
回复 使用道具 举报
黑马王鹏 发表于 2012-12-19 18:16
notifyAll()不会唤醒那个等待的线程么?

那是else里面的语句,你后面又执行不到了,
如果想的话可以放到while(true){}里面
回复 使用道具 举报
孙辉辉 发表于 2012-12-19 19:23
那是else里面的语句,你后面又执行不到了,
如果想的话可以放到while(true){}里面 ...

不对呀,应该会有两个线程同时运行呀,第一个线程睡2秒的时候,第二个线程就可能已经开启了,处于等待时期了,然后被第一个线程所唤醒了,这里面会不会有线程锁的问题呀,不是同一个锁,所以唤不醒,弄不懂!???求解
回复 使用道具 举报
我们可以来看看里面的线程
  1. class Waiting implements Runnable {
  2.         boolean flag = false;

  3.         public synchronized void run() {
  4.         if (flag) {
  5.         flag = false;
  6.         System.out.println(Thread.currentThread().getName());
  7.         System.out.print("1");
  8.         try {
  9.         this.wait();
  10.         } catch (Exception e) {
  11.         }
  12.         System.out.println(Thread.currentThread().getName());
  13.         System.out.print("2");
  14.         } else {
  15.         flag = true;
  16.         System.out.println(Thread.currentThread().getName());
  17.         System.out.print("3");
  18.         try {
  19.         Thread.sleep(2000);
  20.         } catch (Exception e) {
  21.         }
  22.         System.out.println(Thread.currentThread().getName());
  23.         System.out.print("4");
  24.         notifyAll();
  25.         }
  26.         }
  27. }
复制代码

结果
现在是运行到输出1,这时候是线程1等待,没有人能叫醒他了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马