刚开始学多线程,今天在网上看到了下面这个例子,给出的解释是 static 的锁是在 Counter.class 里,非 static 的锁是在 this object 里,它们两个可以同时使用,所以会导致线程不安全。我想问的是在什么样的具体实例里调用这两个方法会导致线程不安全,比如我有线程 1 和线程 2,我想让线程 1 调用 setter,然后线程 2 再调用 getter。在这种情况下,就算都上 static synchoronized 锁,我也不能保证调度器一定先调用线程 1,再调用线程 2 啊?跟不上锁有什么区别?我可以都不上锁,然后调用线程 1 执行 setter,再调用线程 2 执行 getter。
求大佬们指点!!多谢了!
代码如下:
public class Counter{
private static int count = 0;
public static synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
原文 link: https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html
求大佬们指点!!多谢了!
代码如下:
public class Counter{
private static int count = 0;
public static synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
原文 link: https://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html
