我正在学习编写线程安全程序以及如何评估非线程安全的代码。
如果一个类在由多个线程执行时正确运行,则该类被认为是线程安全的。
My Counter.java 不是线程安全的,但是所有 3 个线程的输出均按预期打印为 0-9。
谁能解释一下为什么?线程安全如何工作?
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public void decrement() {
count--;
}
public void print() {
System.out.println(count);
}
}
public class CountThread extends Thread {
private Counter counter = new Counter();
public CountThread(String name) {
super(name);
}
public void run() {
for (int i=0; i<10; i++) {
System.out.print("Thread " + getName() + " ");
counter.print();
counter.increment();
}
}
}
public class CounterMain {
public static void main(String[] args) {
CountThread threadOne = new CountThread("1");
CountThread threadTwo = new CountThread("2");
CountThread threadThree = new CountThread("3");
threadOne.start();
threadTwo.start();
threadThree.start();
}
}
最佳答案
您的Counter
不会通过3个线程共享,相反,每个线程都有一个唯一的Counter
关于Java 线程安全计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15852123/