링크 된 목록에서 최대 값을 찾으려고하는 각각 4 개의 스레드가 있습니다. 왜이 변수를 동기화해야합니까?
이
내 스레드 클래스입니다 :public class MyThread extends Thread {
LinkedList<Integer> list;
int max = Integer.MIN_VALUE;
public MyThread(LinkedList<Integer> list) {
this.list = list;
}
public void run() {
synchronized (list) { /* If I don't synchronize list, I get a NoSuchElementException at list.remove() */
while (!list.isEmpty()) {
int num = list.remove();
if (num > max) {
max = num;
}
}
}
}
}
그리고 여기에 주요 방법으로 클래스 : 위의 코드에서
public class Application {
public static void main(String args[]) throws InterruptedException {
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
MyThread t1 = new MyThread(list);
MyThread t2 = new MyThread(list);
MyThread t3 = new MyThread(list);
MyThread t4 = new MyThread(list);
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println(t1.max);
System.out.println(t2.max);
System.out.println(t3.max);
System.out.println(t4.max);
}
}
, 나는 run 메소드 내에서 list
변수를 동기화 할 수 있습니다 그렇지 않으면 NoSuchElementException
이 list.remove()
에 도착합니다. 왜 이런 경우입니까?
각 스레드마다 고유 한 목록이 없으므로 스레드 간섭이 없습니다.
감사합니다.
각각의'MyThread' 생성자는 동일한리스트 참조로 호출되므로, 모든 쓰레드는 같은리스트를 사용할 것입니다. – korolar
각'Thread'에'List'를 넘겨 주면 왜 각자 자신의 복사본이 있다고 생각합니까? –
[Javadoc 읽기] (https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html), 특히 굵게 표시된 비트는 "**이 구현은 동기화되었습니다. ** ". –