동기화 된 블록을 이해할 수 있도록 도움이 필요합니다. 다음 예 가정 :자바 스레드 : synchronized blocks
public class ThreadStarter {
public static void main(String[] args) {
Queue queueObject = new Queue();
ThreadA thread1 = new ThreadA(queueObject);
ThreadA thread2 = new ThreadA(queueObject);
ThreadB thread3 = new ThreadB(queueObject);
ThreadB thread4 = new ThreadB(queueObject);
thread1.start();
thread2.start();
}
}
public class Queue {
Object[] the theQueue;
public Queue(int size){
theQueue = new Object[size];
}
public submitObject(Object o){
/* add Object to the queue */
}
public deleteObject(int objectId){
/*delete Object from the queue */
}
}
public class ThreadA extends Thread {
private Queue queue;
public ThreadA(Queue queue){
this.queue = queue;
}
public void run() {
while(!isInterrupted()){
synchronized(queue) {
Object o = new Object
queue.submitObject(o);
/* do some other stuff */
}
try {
sleep((int)(Math.random()*1000));
} catch (interruptedException) {
Thread.currentThread().interrupt;
}
synchronized(queue) {
/* do some other stuff on the queue */
}
}
}
}
public class ThreadB extends Thread {
private Queue queue;
public ThreadB(Queue queue){
this.queue = queue;
}
public void run() {
while(!isInterrupted()){
synchronized(queue) {
queue.deleteObject(o);
/* do some other stuff */
}
try {
sleep(1000);
} catch (interruptedException) {
Thread.currentThread().interrupt;
}
}
}
}
내 질문은, 안전을 위해, 큐 클래스에 개체를 제출 ThreadA에서 전체 큐 개체를 동기화 충분히입니까? ThreadB에서 큐에서 객체를 삭제하기 위해 동일한 작업을 수행했습니다. 또는 Queue 클래스의 submitObject() 및 deleteObject() 메서드를 동기화해야합니까?
위와 같이 스레드의 전체 Queue 클래스를 잠그면, 안전한 측면에 있어야합니다. 맞습니까?
greetZ 및 미리 감사드립니다.
+1 : 동기화를 캡슐화할수록 더 쉽고 안전합니다. –
'queue'의 메소드를 동기화하는 것과 기능상 동일하지 않습니다. 그가 그렇게했다면 각'synchronized '섹션에서 발견되는'/ * do some other stuff * /'는 중요한 섹션에 있지 않고 병렬로 실행될 수 있습니다. 해당 코드의 내용에 따라 동기화하는 것이 중요 할 수도 있습니다. 이는 동기화 된 목록과 유사합니다. 반복적으로 여러 작업을 수행하려는 경우 (예 : 반복 작업) 여전히 목록에서 외부 동기화해야합니다. –
@MaxPeters 완전히 동의합니다. – assylias