Java 在使用前如何检查BlockingQueue head元素?

Java 在使用前如何检查BlockingQueue head元素?,java,multithreading,producer-consumer,blockingqueue,Java,Multithreading,Producer Consumer,Blockingqueue,我想在服用前检查头部元素,但升高 java.lang.NullPointerException偷看时 使用java BlockingQueue BlockingQueue sharedQueue = new LinkedBlockingQueue() 这是我的密码,有什么想法吗 while(true){ try { if(!sharedQueue.isEmpty()){ char ch = (char)sharedQueue.peek();

我想在服用前检查头部元素,但升高
java.lang.NullPointerException
偷看时

使用java BlockingQueue

 BlockingQueue sharedQueue = new LinkedBlockingQueue()
这是我的密码,有什么想法吗

while(true){
    try {
        if(!sharedQueue.isEmpty()){
            char  ch = (char)sharedQueue.peek();
            if(Character.isDigit(ch)){
                digitTextField.setText(digitTextField.getText()+sharedQueue.take());
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
    }
}
未找到元素时返回
null

返回:此队列的头,如果此队列为空,则返回null

您需要使用:

    if(ch != null && Character.isDigit(ch)){
未找到元素时返回
null

返回:此队列的头,如果此队列为空,则返回null

您需要使用:

    if(ch != null && Character.isDigit(ch)){

这是因为您正在强制转换为不允许空值的
char
。另外,不要做
sharedQueue.isEmpty()
,后面跟着
peek
——这就是众所周知的“检查然后行动”,这是引起比赛的原因

您应该将
sharedQueue
定义为
BlockingQueue
,然后使用


如果((Character c=sharedQueue.poll())!=null)

这是因为您正在强制转换到不允许为null的
char
。另外,不要做
sharedQueue.isEmpty()
,后面跟着
peek
——这就是众所周知的“检查然后行动”,这是引起比赛的原因

您应该将
sharedQueue
定义为
BlockingQueue
,然后使用

if((字符c=sharedQueue.poll())!=null)