2014-11-24 2 views
1

다음 코드는 "동기화"에 대한 액세스가 모든 스레드에서 동기화되도록해야합니다.스레드간에 동기화

출력에 따르면 스레드 3과 스레드 4가 동일한 sync 값을 읽는 방법에주의해야합니다.

코드에 뭔가 빠졌습니까? 여기

[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

답변

6

. 그래서 효과적으로 동기화되지 않습니다. 모든 잠금이 있어야하므로 동기화 변수가 최종적으로 만들어지면 코드가 더 이상 컴파일되지 않는다는 것을 알 수 있습니다.

해결책 : 다른 최종 객체와 동기화하거나 AtomicInteger를 사용하여 값을 변경하거나 this에 동기화합니다 (즉, 메소드를 동기화).

3

정수는 변경할 수없는 클래스이며 동기화 ++를 수행 할 때 새로운 참조를 동기화에 할당하고 다른 스레드가 이전 동기화에 대한 참조를 보유 할 수 있으므로 멀티 스레딩 문제가 발생합니다. 다음과 같이 INTEGER와 같은 간단한 MUTEX를 정의 해보십시오.

private final Integer MUTEX = new Integer(1); 

동기화 중에 동기화하는 대신 사용하십시오.

+0

이것은 단지 코드가 컴파일되지 않게합니다 ...? –

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); 
    } 
} 

... 
관련 문제