有些参考是说下列代码运行存在线程安全问题,原因是index++
非原子操作且会在println
外执行所以不能保证安全,有的参考书说会在println
内执行所以是安全的,我试了10次以上并且观察数据并没有出现安全问题,例如重复、省略、超出最值的问题,那么这个代码到底是安全的吗?
public class Task implements Runnable {
private int index = 1;
private final static int MAX = 100_000;
@Override
public void run() {
while (index <= MAX) {
System.out.println(Thread.currentThread() + " 的号码是:" + (index++));
}
}
public static void main(String[] args) {
final Task task = new Task();
Thread windowThread1 = new Thread(task, "一号窗口");
Thread windowThread2 = new Thread(task, "二号窗口");
Thread windowThread3 = new Thread(task, "三号窗口");
Thread windowThread4 = new Thread(task, "四号窗口");
windowThread1.start();
windowThread2.start();
windowThread3.start();
windowThread4.start();
}
}
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
可以看一下这篇文章
System.out.println对线程安全的影响