我尝试创建一个扩展线程的类,它只需要一个字符串数组并交替打印前 2 个字符串以进行 10000 次迭代。我使用 AtomicInteger(计数器)跟踪要打印的索引,但是输出有时会打印:hello hello hello w hello hello 等,而不是在每次迭代时交替。为什么会这样?如果不将“同步”放在运行方法中,我该如何解决?
public class MyThreadDelegate implements Runnable {
List<String> words;
AtomicInteger counter = new AtomicInteger(0);
public MyThread(List<String> words) {
this.words = words;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(words.get(counter.getAndIncrement()%2) + counter.get());
}
}
public static void main(String[] args) {
MyThreadDelegate myThreadDelegate = new MyThreadDelegate(Arrays.asList("hello", "w"));
Thread t1 = new Thread(MyThreadDelegate);
Thread t2 = new Thread(MyThreadDelegate);
t1.start();
t2.start();
}
}