다음 코드는 "동기화"에 대한 액세스가 모든 스레드에서 동기화되도록해야합니다.스레드간에 동기화
출력에 따르면 스레드 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();
}
}
}
에 동기화해야합니까? – SMA