中易网

关于synchronized的问题 线程同步!~

答案:2  悬赏:20  
解决时间 2021-04-27 16:51
  • 提问者网友:放荡不羁
  • 2021-04-27 11:20

import java.util.*;

public class tt extends Thread {
timmer t = new timmer();

public tt() {

}

public tt(String n) {
this.setName(n);
}

public void run() {
t.go();
}

public static void main(String args[]) {
tt t1 = new tt("帐三");
t1.start();
tt t2 = new tt("李四");

t2.start();

}
}

class timmer {
public void go() {
synchronized (this) {
for (int i = 0; i < 1000; i++) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(Thread.currentThread().getName());
System.out.println("取出1W元");
}
}

}
}

最佳答案
  • 二级知识专家网友:零负荷的放任
  • 2021-04-27 11:49

你锁的对象是this,而this就timmer 类,你new了两个 tt()类。j也就是有两个timmer 存在了。你加锁的不是同一个对象



你把timmer 作为参数通过构造器传进去,不要在内部new 这样timmer 就是一个了

全部回答
  • 1楼网友:飘零作归宿
  • 2021-04-27 13:03

当然没有锁住线程对象,需要共同调用一个类才会锁,你看

tt t1 = new tt("帐三"); t1.start(); tt t2 = new tt("李四");

t2.start(); 每一个类都用

timmer t = new timmer();

所以没有锁

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息