for循环使用start和join会影响结果
来源:6-6 把普通变量升级为原子变量

灵森
2020-04-01
public class AtomicIntegerFileldUpdaterDemo implements Runnable {
static Candidate tom;
static Candidate peter;
public static AtomicIntegerFieldUpdater scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, “score”);@Override public void run() { for (int i = 0; i < 10000; i++) { tom.score++; scoreUpdater.getAndIncrement(peter); } } @SneakyThrows public static void main(String[] args) { AtomicIntegerFileldUpdaterDemo r = new AtomicIntegerFileldUpdaterDemo(); tom = new Candidate(); peter = new Candidate(); /*Thread thread = new Thread(r); Thread thread2 = new Thread(r); thread.start(); thread2.start(); thread.join(); thread2.join();*/ /*使用for循环每次都是打印20000*/ for (int i = 0; i < 2; i++) { Thread s=new Thread(r); s.start(); s.join(); } System.out.println("普通变量:"+tom.score); System.out.println("升级后的变量:"+peter.score); } static class Candidate { volatile int score; }
}
打印:
普通变量:20000
升级后的变量:20000
老师这里在for循环中执行s.start,s.join,多次打印出来的tom和peter的score都是20000。
把两个线程分别start和join就没有问题,是什么原因呢?
写回答
1回答
-
s.start();
s.join();代表每个线程都完成运行后才运行下一个线程,无并发了。
122020-04-01
相似问题