下面是我的测试代码,无法测试到不可见的情况,是根本不存在还是太短抓不到
public class TestClass {
public int num = 0;
}
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
private static final AtomicInteger threadNumber = new AtomicInteger(1);
static Executor executor = new ThreadPoolExecutor(100, 100, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("test" + threadNumber.getAndAdd(1));
return thread;
}
});
public static void main(String[] args) {
TestClass testClass = new TestClass();
executor.execute(new Runnable() {
@Override
public void run() {
testClass.num = 10;
}
});
for(int i = 1;i<1000000000000L;i++)
executor.execute(new Runnable() {
@Override
public void run() {
if(testClass.num != 10) {
System.out.println(testClass.num);
}
}
});
}
}
需要加锁才成。