여러 스레드와 동기화를 사용하는 방법을 찾고 있습니다. wait() 및 notify()를 사용하여 시도했지만 스레드가 여전히 동기화되지 않습니다. 큰 프로젝트가 있지만 간단히 말해 setter 메서드 (이 경우에는 thread1)로 미리 지정된 횟수만큼 스레드를 실행하고 각 "set"후에 getter 메서드 (thread2)를 실행하여 객체를 가져옵니다. 다른 많은 예를 살펴 보았지만 제대로 작동하지 않는 것 같습니다. 따라서 이것이 도움이되지 않는 이유에 대한 도움이나 설명이 도움이 될 것입니다.1 클래스의 동기화 된 스레드
가끔씩 thread1이 먼저 실행되지만 다른 몇 번 먼저 thread2가 실행되어 동기화가 작동하지 않는 경우가 있습니다.
감사합니다.
import java.util.ArrayList;
public class ThreadTest{
private ArrayList<Object> myList;
public ThreadTest(){
myList = new ArrayList<Object>();
Thread thread1 = new Thread(){
public void run(){
for(int i = 0; i < 10; i++){
addToList("" + i);
}
}
};
Thread thread2 = new Thread(){
public void run(){
for(int i = 0; i < 10; i++){
System.out.print(myList.get(i) + " ");
}
}
};
thread1.start();
thread2.start();
}
public synchronized void addToList(String a){
myList.add(a);
notify();
}
public synchronized ArrayList<Object> getList(){
try{
wait();
}
catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return myList;
}
public static void main(String[] args){
new ThreadTest();
}
}
'getList()'메소드의 목적은 무엇입니까? 당신은 그것을 사용하지 않습니다. – bsiamionau
바퀴를 재발 명하지 마십시오. ['BlockingQueue'] (http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html) –
@ bmorris591 그러나 사각형 휠을 원하면 어떻게합니까?) –