Java中的线程执行

时间:2018-09-06 11:06:15

标签: java multithreading

问题陈述: 有n个线程,n / 2个线程是生产者,n / 2个消费者,生产者1线程产生的数字必须由消费者1线程消费。线程也必须按顺序运行,生产者1,然后是消费者1,再次是生产者2,然后是消费者2…依此类推……。

我正在使用线程在Java中实现生产者消费者,但要求是有N / 2个生产者线程和N / 2个消费者线程,N个消费者线程应消耗N个生产者产生的值,n-1个消费者线程应消耗n个-1生产者价值。

我已经使用阻塞队列实现了此操作,但没有得到所需的输出:

package paytm;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerWithBlockingQueue {
public static class Producer implements Runnable {
    private BlockingQueue<Integer> queue;
    private int next = 0;
    private String thereadName;
    public Producer(BlockingQueue<Integer> queue,String threadName) {
            this.queue = queue;
            this.thereadName = threadName;
    }

    @Override
    public void run() {
            while (true) {
                    try {
                            if(next<10) {
                            queue.put(next);
                            System.out.println(thereadName+ " "+ next);
                            }


                    } catch (InterruptedException e) {
                    }
                    next++;
            }
    }
 }
public static class Consumer implements Runnable {
    private BlockingQueue<Integer> queue;
    private String thereadName;
    public Consumer(BlockingQueue<Integer> queue,String threadName) {
            this.queue = queue;
            this.thereadName = threadName;
    }

    @Override
    public void run() {
            while (true) {
                    synchronized (queue) {
                            Integer next;
                            try {
                                    next = queue.take();
                                    System.out.println(thereadName+ " "+ next);
                            } catch (InterruptedException e) {
                            }
                    }
            }
     }
}

 public static void main(String args[]) throws Exception {
    BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(1);
    Thread producer1 = new Thread(new Producer(queue,"producer1"));
    Thread producer2 = new Thread(new Producer(queue,"producer2"));
    Thread consumer1 = new Thread(new Consumer(queue,"Consumer1"));
    Thread consumer2 = new Thread(new Consumer(queue,"Consumer2"));
    producer1.start();
    producer2.start();
    consumer1.start();
    consumer2.start();

//        producer1.join();
//        producer2.join();
//        consumer1.join();
//        consumer2.join();
}
}

// Output :
 producer1 0
 consumer1 0
 producer2 1
 consumer2 1
 producer3 2
 consumer3 2   so on...

1 个答案:

答案 0 :(得分:1)

这可能无法完成您期望的操作:

while (true)
    synchronized(queue) {
        ...
    }
}

让我们假设consumer1赢得比赛,进入synchronized块,而consumer2被迫等待。您假设consumer1做事然后从synchronized块退出时会发生什么?

Java语言规范没有说明在那种情况下必须发生的情况,但是在大多数实现中,实际发生的情况是,consumer1将直接回到{{1}之前的synchronized块中}甚至开始醒来。

Java中的内在锁不是 fair