我正在学习编写线程安全程序以及如何评估非线程安全的代码。Java线程安全计数器
如果一个类在由多个线程执行时正常工作,则该类被认为是线程安全的。
我的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();
}
}
您正在使用每个线程不同的计数器对象,这就是为什么你没有看到在这种情况下,任何线程安全问题。 – Leon 2013-04-06 14:35:38