2014-11-24 101 views
1

以下代碼應確保跨所有線程同步對「同步」的訪問。跨線程同步

根據a輸出,並非總是如此,請注意Thread-3和Thread-4如何讀取相同的同步值。

我在代碼中丟失了什麼嗎?

[Thread-0] before value of sync is 0 
[Thread-0] after value of sync is 1 
[Thread-3] before value of sync is 1 
[Thread-3] after value of sync is 2 
[Thread-4] before value of sync is 1 
[Thread-4] after value of sync is 3 
[Thread-2] before value of sync is 3 
[Thread-2] after value of sync is 4 
[Thread-1] before value of sync is 4 
[Thread-1] after value of sync is 5 

這裏的代碼:

package com.mypackage.sync; 

public class LocalSync implements Runnable { 

    private Integer sync = 0; 

    public void someMethod() { 
     synchronized (sync) { 
      System.out.println("[" + Thread.currentThread().getName() + "]" + " before value of sync is " + sync); 
      sync++; 
      System.out.println("[" + Thread.currentThread().getName() + "]" + " after value of sync is " + sync); 
     } 
    } 

    @Override 
    public void run() { 
     someMethod(); 
    } 

    public static void main(String[] args) { 

     LocalSync localSync = new LocalSync(); 
     Thread[] threads = new Thread[5]; 
     for (int i = 0; i < threads.length; i++) { 
      threads[i] = new Thread(localSync, "Thread-" + i); 
      threads[i].start(); 
     } 

    } 
} 
+2

同步你知道同步即整數包裝是不可變的? – SMA 2014-11-24 13:06:31

回答

6

你不斷改變其上的所有線程都應該是同步的同步對象。所以,實際上,它們根本不同步。讓每個鎖都應該是最後的同步變量,然後你會看到你的代碼不再編譯。

解決方案:在另一個最終對象上同步,或者使用AtomicInteger並更改其值,或者在this上同步(即使該方法同步)。

3

Integer是不可變的類,當您在執行synC++時,您正在爲Sync分配一個新的引用,並且您的其他線程可能會持有對較舊同步的引用,因此會引發多線程問題。嘗試定義一個說INTEGER的簡單MUTEX,如:

private final Integer MUTEX = new Integer(1); 

並用它代替同步同步。

+0

這只是使代碼不能編譯...? – 2014-11-24 13:42:24

0

你應該上Object

private Object synchObj = new Object(); 
private Integer sync = 0; 

public void someMethod() { 
    synchronized (synchObj) { 
     System.out.println("[" + Thread.currentThread().getName() + "]" + " before value of sync is " + sync); 
     sync++; 
     System.out.println("[" + Thread.currentThread().getName() + "]" + " after value of sync is " + sync); 
    } 
} 

...