I need some help to make sure that I understand synchronized blocks. Assuming the following Example:
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;
}
}
}
}
My Question is, is it enough to synchronize the whole queue object in ThreadA to submit an object to the queue class, to be on the safe side? I have done the same in ThreadB to delete an object from the queue. Or do i have to synchronize the submitObject() and the deleteObject() method in the Queue class, too?
In my understanding, if I lock the whole Queue class in the threads as shown above, I should be on the safe side - right?
greetZ and thanks in advance.