2015-10-14 55 views
0

例一爲什麼這個線程是不是安全

public class Test { 
     public static void main(String[] args) { 
       ExecutorService pool = Executors.newFixedThreadPool(2); 
       Runnable t1 = new MyRunnable("A", 2000); 
       Runnable t2 = new MyRunnable("B", 3600); 
       Runnable t3 = new MyRunnable("C", 2700); 
       Runnable t4 = new MyRunnable("D", 600); 
       Runnable t5 = new MyRunnable("E", 1300); 
       Runnable t6 = new MyRunnable("F", 800); 

       pool.execute(t1); 
       pool.execute(t2); 
       pool.execute(t3); 
       pool.execute(t4); 
       pool.execute(t5); 
       pool.execute(t6); 

       pool.shutdown(); 
     } 
} 

class MyRunnable implements Runnable { 
     private static AtomicLong aLong = new AtomicLong(10000); 
     private String name;    
     private int x;      

     MyRunnable(String name, int x) { 
       this.name = name; 
       this.x = x; 
     } 

     public void run() { 
       System.out.println(name + " excute" + x + ",money:" + aLong.addAndGet(x)); 
     } 
} 

這個線程不是此示例中的安全。

例二

public class CountingFactorizer implements Servlet { 
    private final AtomicLong count = new AtomicLong(0); 

    public void service(ServletRequest req, ServletResponse resp) { 
     count.incrementAndGet(); 
    } 
} 

這是爲什麼線程安全的?有人可以告訴我?

我在java學習線程,但不能理解兩個樣本。他們不一樣嗎?

+2

你爲什麼認爲例子1不是線程安全的? – dkatzel

+0

@dkatzel,你可以在eclipse中運行它,大部分時間都是正確的。 **但是**有時候不安全。 – william

+3

不安全如何?只是因爲它以不同的順序執行並不意味着它不是線程安全 – dkatzel

回答

1

據我所見,兩者都是線程安全的。在這兩個示例中,靜態,類級別,成員是AtomicLong,根據定義它是線程安全的。第一個例子中的所有其他成員都是實例級別的成員,並在不同的線程中執行,因此根本沒有衝突。

相關問題