如果不进行volatile保证可见,Java系统内值的不可见会保持多久?

如下代码我无法测试出这段时间,是根本不存在还是测试方法不对?

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);

}

}

});

}

}

以上是 如果不进行volatile保证可见,Java系统内值的不可见会保持多久? 的全部内容, 来源链接: utcz.com/p/944305.html

回到顶部