标题:t1的sharevar怎么会为10?
只看楼主
cy2047
Rank: 1
等 级:新手上路
帖 子:18
专家分:0
注 册:2006-6-17
 问题点数:0 回复次数:1 
t1的sharevar怎么会为10?

public class tt implements Runnable {
public static int shareVar = 0;
public synchronized void run() {
if (shareVar == 0) {
for (int i = 0; i < 10; i++) {
shareVar++;
if (shareVar == 5) {
try {
this.wait(); }
catch (Exception e) {}
}//if
} //for
} //if
if (shareVar != 0) {
System.out.print(Thread.currentThread().getName());
System.out.println(" shareVar = " + shareVar);
this.notify();
}
} //run

public static void main(String[] args) {
Runnable r = new tt();
Thread t1 = new Thread(r, "t1");
Thread t2 = new Thread(r, "t2");
t1.start();
t2.start();
}
}

t1线程最先执行。由于初始状态下shareVar为0,t1将使shareVar连续加1,当shareVar的值为5时,t1调用wait() 方法, t1将处于休息状态,同时释放锁标志。这时t2得到了锁标志开始执行,shareVar的值已经变为5,所以t2直接输出shareVar的值,
然后再调用notify() 方法唤醒t1。t1接着上次休息前的进度继续执行,但是此时静态变量为5而不是0,应该是不会再累加了,为什么会继续累加到十?

搜索更多相关主题的帖子: public 
2006-06-23 10:19
千里冰封
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:灌水之王
等 级:版主
威 望:155
帖 子:28477
专家分:59
注 册:2006-2-26
得分:0 
当然会往上加,当等于5的时候会停一次,但是又被唤醒了
这个时候,它先自己加一次,这个时候已经不等于5了,所以它不会再wait了,所以一直会执行到10为止

可惜不是你,陪我到最后
2006-06-23 11:28



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-74236-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.273294 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved