如何在java中停止生产者和消费者中的线程?

时间:2015-01-12 20:46:25

标签: java multithreading

这是我的消费者类

我不知道如何在生产产品之前停止线程? (睡眠似乎不起作用)

请建议我使用除阻塞队列接口和睡眠方法之外的其他方法

package producerconsumer;
import java.util.Scanner;

public class Consumer implements Runnable {

    Thread t;
    String consumerName;

    public Consumer(String name) {
        t = new Thread(this, name);
        t.start();

    }

    @Override
    public  void run() {
        int m = Producer_consumer.n;
        try {
            if (m!=0) {
                Producer_consumer.delay.acquire();
            } else {
                Thread.sleep(100);//??
            }

            while (true) {
                Producer_consumer.criticalSection.acquire();
                consumerName = Thread.currentThread().getName();
                consume();
                Producer_consumer.n--;
                Producer_consumer.form.setLable(Producer_consumer.n + "");
                m = Producer_consumer.n;
                Producer_consumer.criticalSection.release();
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要wait()表示条件,并在条件发生变化时发出notify()。以下是一个例子:

http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

public class Drop {
    // Message sent from producer
    // to consumer.
    private String message;
    // True if consumer should wait
    // for producer to send message,
    // false if producer should wait for
    // consumer to retrieve message.
    private boolean empty = true;

    public synchronized String take() {
        // Wait until message is
        // available.
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        // Toggle status.
        empty = true;
        // Notify producer that
        // status has changed.
        notifyAll();
        return message;
    }

    public synchronized void put(String message) {
        // Wait until message has
        // been retrieved.
        while (!empty) {
            try { 
                wait();
            } catch (InterruptedException e) {}
        }
        // Toggle status.
        empty = false;
        // Store message.
        this.message = message;
        // Notify consumer that status
        // has changed.
        notifyAll();
    }