无法在另一个线程后启动执行程序

时间:2018-02-22 14:36:44

标签: java multithreading

当我在代码下面运行时,Producer run()方法启动并将随机数放入作业队列,但Consumer run()方法永远不会运行。这里的主要问题是什么?

这是Main class;

public static LinkedBlockingQueue<Integer> jobs = new LinkedBlockingQueue<>();

public static void main(){

    MessageProducer producer = new MessageProducer(jobs);
    Thread producerThread = new Thread(producer);
    producerThread.run();

    MessageConsumer consumer = new MessageConsumer(jobs);
    Executor executor = Executors.newFixedThreadPool(3);
    executor.execute(consumer);

}

生产者;

public class MessageProducer implements Runnable {

    public LinkedBlockingQueue<Integer> jobs;

    public MessageProducer(LinkedBlockingQueue<Integer> jobs){
        this.jobs = jobs;
    }

    @Override
    public void run() {
        while(true) {
            try {
                jobs.put((int) (Math.random() * 10));
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

消费;

public class MessageConsumer implements Runnable{

    public LinkedBlockingQueue<Integer> jobs;

    public MessageConsumer(LinkedBlockingQueue<Integer> jobs) {
        this.jobs = jobs;
    }


    @Override
    public void run() {
        while(true) {
            System.out.println("Executing " + jobs.poll());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

不要调用Thread.run()。它没有启动线程。它调用run()方法,在您的情况下是无限循环 因此,JVM始终停留在永不返回的producerThread.run();上。

而是调用负责调用Thread.start()方法的run()

Thread.start() javadoc确实说明了:

  

使该线程开始执行; Java虚拟机调用   这个线程的run方法。