我需要一些帮助来确保我理解同步块。假设以下示例:
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 并提前致谢。