原子/易失性/同步如何在内部工作?
以下代码块之间有什么区别?
代码1
private int counter;
public int getNextUniqueIndex() {
return counter++;
}
Run Code Online (Sandbox Code Playgroud)
代码2
private AtomicInteger counter;
public int getNextUniqueIndex() {
return counter.getAndIncrement();
}
Run Code Online (Sandbox Code Playgroud)
代码3
private volatile int counter;
public int getNextUniqueIndex() {
return counter++;
}
Run Code Online (Sandbox Code Playgroud)
是否volatile以下列方式工作?是
volatile int i = 0;
void incIBy5() {
i += 5;
}
Run Code Online (Sandbox Code Playgroud)
相当于
Integer i = 5;
void incIBy5() {
int temp;
synchronized(i) { temp = i }
synchronized(i) { i = temp + 5 }
}
Run Code Online (Sandbox Code Playgroud)
我认为两个线程不能同时进入同步块...我是对的吗?如果这是真的那么如何atomic.incrementAndGet()工作没有synchronized …
我读了一些java代码,发现了这些函数:
synchronized void setConnected(boolean connected){
this.connected = connected;
}
synchronized boolean isConnected(){
return connected;
}
Run Code Online (Sandbox Code Playgroud)
我想知道这里的同步是否有意义,或者只是作者不理解synchronized关键字的必要性?
我想在这里同步是没用的.还是我弄错了?
我有一个像这样的Java类:
public class Foo {
public static int counter = 0;
public void bar(int counter) {
Foo.counter = counter;
}
}
Run Code Online (Sandbox Code Playgroud)
FindBugs警告我counter通过实例方法写入静态字段bar.但是,如果我将代码更改为:
public class Foo {
public static int counter = 0;
public static void setCounter(int counter) {
Foo.counter = counter;
}
public void bar(int counter) {
setCounter(counter);
}
}
Run Code Online (Sandbox Code Playgroud)
然后FindBugs不会抱怨.这不是错的吗?我仍然通过静态方法从实例方法写入静态字段,不是吗?
我最近偶然发现了一篇题为" 同步访问可变字段 "的文章.它声称:
例如,在多线程环境中,可变字段的all
get和set方法通常应该是synchronized方法.这包括原始字段.
我的问题是为什么?同步getId方法有什么用?或者如果我不同步它会发生什么.
例如,我传递UserContext给Spring Service函数并getUserId在函数内调用.如果getUserId不同步,这可能是一个问题吗?
我很难理解同步如何在同一个对象的两个不同方法上工作.我有一个类,有两个声明为synchronized的实例方法.三个线程访问此对象的两个同步方法,但结果是意外的.线程可以互换地访问这两种方法.它们不等待释放整个对象的锁定.这是样本:
public class ThreadSafeCounterSameMonitor2 {
private int value;
public synchronized int getValue() {
return this.value;
}
public synchronized void setValue(int value) {
this.value = value;
}
public static void main(String[] args) {
ThreadSafeCounterSameMonitor2 nts = new ThreadSafeCounterSameMonitor2();
Thread th1 = new Thread(new Runnable() {
public void run() {
nts.setValue(5);
System.out.println("Thread Id " + Thread.currentThread().getId() + ", expected value is 5, value=" + nts.getValue());
}
});
Thread th2 = new Thread(new Runnable() {
public void run() {
nts.setValue(10);
System.out.println("Thread Id " …Run Code Online (Sandbox Code Playgroud)