2014-11-24 117 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); 
    } 
} 

...