想用代码演示出并发的有序性问题,代码如下
public class ConCurrentTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
ExecutorService executorService = Executors.newFixedThreadPool(2);
scheduledExecutorService.scheduleWithFixedDelay(()->{
try {
MyTest mt = new MyTest();
CountDownLatch cd = new CountDownLatch(1);
CountDownLatch cd1 = new CountDownLatch(2);
executorService.execute(() -> {
try {
cd.await();
mt.test1();
cd1.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.execute(() -> {
try {
cd.await();
mt.test2();
cd1.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
cd.countDown();
cd1.await();
if (mt.getC() == 0) {
System.out.println("a="+mt.getA());
System.out.println("b="+mt.getB());
System.out.println("c="+mt.getC());
}
} catch (Exception e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
}
}
class MyTest {
private int a = 0;
private boolean b = false;
private int c = 0;
public void test1(){
a = 1;
b = true;
}
public void test2(){
while (!b);
c = a;
}
public int getA() {
return a;
}
public boolean getB() {
return b;
}
public int getC() {
return c;
}
}
正常情况自然是a=1, c=1;
但应该也会出现a=1,c=0;的情况呀,我这始终没出现预期效果
跑了下你的代码,按我理解你想展示的意思是,
最外面的定时线程池用来循环调用。
里面线程池2个任务,执行方法前 同时被阻塞了
然后运行cd.countDown(); 同时释放,
然后cd1.await(); 阻塞,直到两个线程任务执行完
至于ABC 01这些,只是用来展示执行顺序吧,源代码中的展示处理有问题,达不到你要的效果
直接输出就好了,在test1、test2方法中直接System.out输出就可以了,偶尔能看到test2先执行