我的初始值不是从1开始,而是保持不变

时间:2019-12-23 10:26:08

标签: java concurrency

这应该是如何工作的,一旦队列收到6罐,它将继续打包并将其存储在一个盒子中,但是当我想显示我的盒子编号时,它将显示我的起始盒子编号为盒子0框1

class Box {
    Can can1, can2, can3, can4, can5, can6;
    int BoxNo;


public Box (Can can1, Can can2, Can can3, Can can4, Can can5, Can can6){
    this.can1 = can1;
    this.can2 = can2;
    this.can3 = can3;
    this.can4 = can4;
    this.can5 = can5;
    this.can6 = can6; 
}

public Box (int BoxNo){
    this.BoxNo = BoxNo;
}
}

class Packaging extends Thread {
    LinkedBlockingQueue<Can>labellingQ;
    LinkedBlockingQueue<Box>packagingQ;

public Packaging (LinkedBlockingQueue<Can> labellingQ, LinkedBlockingQueue<Box> packagingQ){
    this.labellingQ = labellingQ;
    this.packagingQ = packagingQ;
}

public void run(){
    while(true){
        try{
            if(labellingQ.size() == 6){
                    System.out.println("Packaging cans into box ");
                    Can can1 = labellingQ.take();
                    Can can2 = labellingQ.take();
                    Can can3 = labellingQ.take();
                    Can can4 = labellingQ.take();
                    Can can5 = labellingQ.take();
                    Can can6 = labellingQ.take();
                    Thread.sleep(500);
                    System.out.println("Cans have been shrink wrapped");
                    Thread.sleep(500);
                    Box bx = new Box (can1, can2, can3, can4, can5, can6);

                    packagingQ.put(bx);
                    System.out.println("Cans " + can1.CanNo + " " + can2.CanNo + " " + can3.CanNo + " " +can4.CanNo + " " +can5.CanNo + " " +can6.CanNo + " has been packed into box " + bx.BoxNo);
            }
        }catch(Exception e){}
    }
}
}

这是我的输出

Cans 2 6 8 20 25 29 has been packed into box 0

后跟

Cans 33 51 53 54 56 57 has been packed into box 0

1 个答案:

答案 0 :(得分:0)

在Box类中,

class Box {
Can can1, can2, can3, can4, can5, can6;
int BoxNo;


public Box (Can can1, Can can2, Can can3, Can can4, Can can5, Can can6, int boxNo){
    this.can1 = can1;
    this.can2 = can2;
    this.can3 = can3;
    this.can4 = can4;
    this.can5 = can5;
    this.can6 = can6; 
    this.BoxNo = boxNo;
}
}

在while循环中:

int boxNo = 1;
while(true)
{

    //Can codes...
    Box bx = new Box (can1, can2, can3, can4, can5, can6, boxNo);
    boxNo++;
    //print codes...
}