public class TestShare extends Thread {
private int count=5;
@Override
public void run() {
count--;
System.out.println(Thread.currentThread().getName()+" "+count);
}
}
测试一:
public static void main(String[] args) {
TestShare t1 = new TestShare("A");
TestShare t2 = new TestShare("B");
TestShare t3 = new TestShare("C");
TestShare t4 = new TestShare("D");
t1.start();
t2.start();
t3.start();
t4.start();
}
结果:
A 4
B 4
D 4
C 4
测试二:
public static void main(String[] args) {
TestShare share = new TestShare();
Thread t1 = new Thread(share,"A");
Thread t2 = new Thread(share,"B");
Thread t3 = new Thread(share,"C");
Thread t4 = new Thread(share,"D");
t1.start();
t2.start();
t3.start();
t4.start();
}
结果:
A 2
C 1
B 2
D 2
测试说明:测试二中共享了变量count,并且产生了线程安全的问题。而测试一没并没有共享count