JAVA等待/睡眠不被其他线程打断

时间:2014-01-30 11:47:03

标签: java concurrency

我需要你的帮助。

我有2个JAVA课程。在一个类中有一个FIFO列表/队列,两个类都必须并发访问该列表。该列表在class1中。 Class1使用addElementToEndOfQueue。 Class2使用getValueOfQueue来删除队列的头部。

public static synchronized String getValueOfQueue(){
    return queueSend.poll(); 
}

public synchronized boolean addValueToQueue(String s){
    Boolean blnReturn = queueSend.offer(s);
    class2.interrupt();
    return blnReturn;
}

Class2尝试并获取队列的头部值,如果队列为空,则strValue为null并且线程应该等到他被中断bei addValueToQueue:

while(true){
 String strValue = class1.getValueOfQueue();
 if (strValue == null) {
            try {
                wait();}
            catch (InterruptedException e) {
                continue;}
// do things
}

我现在的问题是,如果必须在while循环中等待/睡眠(以模拟延迟)。如果我使用睡眠或等待,可能会发生addValueToQueue中断我,我不希望这样。我希望程序等待给定的时间而不是被打断。我怎样才能做到这一点?或者我现在应该使用完全其他的方法吗? 谢谢你的帮助!

0 个答案:

没有答案
相关问题