import java.util.concurrent.atomic.AtomicInteger;
public class ThreadSafeClass {
public AtomicInteger i=new AtomicInteger(0);
public static void main(String[] args) {
A_AtomicInteger a=new A_AtomicInteger(i);//这里有问题!!
a.run();
}
class A_AtomicInteger implements Runnable{
public AtomicInteger j;
public void run() {
j.addAndGet(1);
System.out.println(j);
}
public A_AtomicInteger(AtomicInteger j) {
super();
this.j = j;
}
}
}
====================
不知道除了什么问题,竟然提示“Cannot make a static reference to the non-static field i”
------解决方案--------------------
主要是嵌套类的可见性,引起的,我改了一下:import java.util.concurrent.atomic.AtomicInteger;
public class ThreadSafeClass {
public static AtomicInteger i=new AtomicInteger(0);
public static void main(String[] args) {
ThreadSafeClass.A_AtomicInteger a=new ThreadSafeClass.A_AtomicInteger(ThreadSafeClass.i);//这里有问题!!
a.run();
}
public static class A_AtomicInteger implements Runnable{//加了一个静态的
public AtomicInteger j;
public void run() {
j.addAndGet(1);
System.out.println(j);
}
public A_AtomicInteger(AtomicInteger j) {
super();
this.j = j;
}
}
}