线程消耗队列,终止

时间:2015-01-16 09:12:58

标签: multithreading terminate blockingqueue

我想知道以下方法是否正确。 我在生产者和消费者线程中使用了常见的BlockingQueue。 生产者是一个嗅探器线程,所以它会自动停止,但我认为消费者认为终止于生产者线程的状态(活着/死)循环。有什么建议?感谢

- )来自主线程:

    ArrayBlockingQueue<PcapPacket> queue = new ArrayBlockingQueue<>(); 
    Producer p = new Producer(queue);
    Thread t1 =new Thread(p);
    t1.start();
    Consumer c = new Consumer(queue,t1);
    new Thread(c).start();

- )制片

public void run() {
         public void nextPacket(PcapPacket packet, String user) {
            try {
                queue.put(packet); 
            } catch (InterruptedException ex) {

            }

- )消费者

public void run() {
   while(producer.isAlive()){
        try {
        //Thread.sleep(50);
        packet=queue.take(); 

1 个答案:

答案 0 :(得分:0)

轮询制作人的状态不是最佳状态。

首选方法是让生产者在生产者退出时,放入一些“毒丸”。进入队列,并让消费者在收到药丸后立即结束它:

class Producer implements  Runnable {

    static final Object TIME_TO_STOP = new Object();

    private final BlockingQueue<Object> q;

    Producer(BlockingQueue<Object> q) {
        this.q = q;
    }


    @Override
    public void run() {
        try {
            while (true) {
                q.put(readNextPacket());
            }
        } finally {
            // exception happened
            try {
                q.put(TIME_TO_STOP);
            } catch (InterruptedException e) {
                // somehow log failure to stop properly
            }
        }
    }
}

class Consumer implements Runnable {

    private final BlockingQueue<Object> q;

    Consumer(BlockingQueue<Object> q) {
        this.q = q;
    }

    @Override
    public void run() {
        while (true) {
            Object packet = q.take();
            if (packet == Producer.TIME_TO_STOP) {
                break;
            }
            // process packet
        }
    }
}