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(); }結果:
測試二:
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(); }結果:
測試說明:測試二中共享了變量count,而且產生了線程安全的問題。而測試一沒並無共享count
安全