實例變量與線程安全


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

測試二:
java

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

安全

相關文章
相關標籤/搜索