JAVA 多线程的问题

来源:互联网 发布:网络贷款不还会怎么样 编辑:程序博客网 时间:2024/05/01 08:09

原地址:http://www.iteye.com/problems/92028

JAVA 多线程的问题0

Java代码 复制代码 收藏代码
  1. public class ReaderResultextends Thread {  
  2.     Calculator c;  
  3.  
  4.     public ReaderResult(Calculator c) {  
  5.             this.c = c;  
  6.     }  
  7.  
  8.     public void run() {  
  9.             synchronized (c) {  
  10.                     try {  
  11.                             System.out.println(Thread.currentThread() +"等待计算结果。。。");  
  12.                             c.wait();  
  13.                     } catch (InterruptedException e) {  
  14.                             e.printStackTrace();  
  15.                     }  
  16.                     System.out.println(Thread.currentThread() + "计算结果为:" + c.total);  
  17.             }  
  18.     }  
  19.  
  20.     public staticvoid main(String[] args) {  
  21.             Calculator calculator = new Calculator();  
  22.             //启动三个线程,分别获取计算结果  
  23.             new ReaderResult(calculator).start();  
  24.             new ReaderResult(calculator).start();  
  25.             new ReaderResult(calculator).start();  
  26.             //启动计算线程  
  27.             calculator.start();  
  28.              
  29.     }  

Java代码 复制代码 收藏代码
  1. public class Calculatorextends Thread {  
  2.     int total;  
  3.     public void run() {  
  4.             synchronized (this) {  
  5.                 System.out.println(total); 
  6.                     for (int i =0; i < 101; i++) {  
  7.                             total += i;  
  8.                     }  
  9.                     System.out.println(total);     
  10.             }  
  11.     }  


就2个简单的类 , 以我的认识,应该在c.wait()这里卡住,也就是说应该不会输出“计算结果为:" ”这些话。  但是为什么他有时候会输出呢?(有时候不会)。 到底是什么破坏了wait 状态?  应该不是start, 因为有时候是先输出System.out.println(total)这里, 然后再打印等待计算结果。。  高人请指点下
多线程
5 小时前
  • Comment添加评论
  • 关注(1)

1个答案      按时间排序按投票排序

00

你将第一个线程类中的同步关键字c换成其他的对象试一下,如object对象。。看能否得到预期的结果?

原创粉丝点击