gpt4 book ai didi

java - 链接的阻塞队列中的值未正确传递

转载 作者:行者123 更新时间:2023-12-01 19:14:16 25 4
gpt4 key购买 nike

这是如何工作的,我的 jar 将进入传送带,然后使用 sanitizer 类进行扫描,但我遇到了问题,因为我的 jar 没有正确通过,这意味着我的一些 jar 没有被扫描,例如:扫描 jar 1后,提示 jar 2已添加到皮带中,但直接跳到 jar 3

public class AsiaPacificFruitFactory {


public static void main(String[] args) {
LinkedBlockingQueue<Can>beltQ = new LinkedBlockingQueue<Can>();
LinkedBlockingQueue<Can>sterilizeQ = new LinkedBlockingQueue<Can>();

Belt b = new Belt(beltQ);
Sterilize s = new Sterilize(beltQ, sterilizeQ);
b.start();
s.start();
}

}

class Belt extends Thread{
LinkedBlockingQueue<Can>beltQ;

public Belt (LinkedBlockingQueue<Can> beltQ){
this.beltQ = beltQ;
}
@Override
public void run(){
while(true){
addCan();
try{
Thread.sleep(500);
}catch (Exception e){}
}
}

public void addCan(){
for (int i=1; i<501; i++){
try{
beltQ.put(new Can(i));
System.out.println("Can " + i + " has been added into the belt" );
Thread.sleep(500);
}catch (Exception e){}
}
}
}

class Scanner implements Callable<Can>{
Can c;

public Scanner (Can c){
this.c = c;
}

Random rand = new Random();

public Can call() throws Exception{
System.out.println("Scanning can " + c.CanNo + " for dents");
c.getDefect();

if(c.defect == 3){
System.out.println("Can " + c.CanNo + " is dented");
return null;
}
else{
System.out.println("Can " + c.CanNo + " is not dented");
return c;
}
}
}

class Sterilize extends Thread{
LinkedBlockingQueue<Can>beltQ;
LinkedBlockingQueue<Can>sterilizeQ;

public Sterilize (LinkedBlockingQueue<Can> beltQ, LinkedBlockingQueue<Can>sterilizeQ){
this.beltQ = beltQ;
this.sterilizeQ = sterilizeQ;
}


public void run(){
while(true){
try{
Can c = beltQ.take();
ExecutorService exe = Executors.newCachedThreadPool();
Future<Can> tempCan = exe.submit(new Scanner(c));
if(tempCan.get() == null){
System.out.println("Can " + c.CanNo + " has not passed the scanning section");
continue;
}else{
sterilizeQ.put(beltQ.take());
}
exe.shutdown();
}catch(Exception e){}
}
}
}

我的输出是这样的:

Can 1 has been added into the belt
Scanning can 1 for dents
Can 1 is not dented
Can 2 has been added into the belt
Can 1 has passed scanning......proceeding with sterilizing now
Can 3 has been added into the belt
Scanning can 3 for dents
Can 3 is not dented
Can 4 has been added into the belt
Can 3 has passed scanning......proceeding with sterilizing now

最佳答案

问题出在 Sterilize run 方法

替换

sterilizeQ.put(beltQ.take());

sterilizeQ.put(c);

关于java - 链接的阻塞队列中的值未正确传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com