在Java中,可以使用以下幾種方式來解決全局變量多線程問題:
public class GlobalVariable {
private static int counter = 0;
public static synchronized void increment() {
counter++;
}
}
public class GlobalVariable {
private static volatile int counter = 0;
public static void increment() {
counter++;
}
}
public class GlobalVariable {
private static ThreadLocal<Integer> counter = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public static void increment() {
counter.set(counter.get() + 1);
}
public static Integer getCounter() {
return counter.get();
}
}
以上是幾種常見的解決全局變量多線程問題的方法,根據具體的場景和需求選擇合適的方法。