Skip to content

Commit 3d6fbae

Browse files
committed
多线程之生产者消费者问题
1 parent 093ec27 commit 3d6fbae

File tree

4 files changed

+90
-0
lines changed

4 files changed

+90
-0
lines changed
1.55 KB
Binary file not shown.
1.72 KB
Binary file not shown.
Binary file not shown.
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package com.duwei.multythread;
2+
3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
import java.util.Random;
6+
/**
7+
* 生产者消费者问题
8+
* http://developer.51cto.com/art/201508/487488.htm
9+
* @author 杜伟
10+
*/
11+
public class ProducerConsumerInJava {
12+
13+
public static void main(String args[]) {
14+
System.out.println("如何在java中使用 wait and notify");
15+
System.out.println("解决生产者消费者问题");
16+
Queue<Integer> buffer = new LinkedList<>();
17+
int maxSize = 10;
18+
Thread producer = new Producer(buffer, maxSize, "PRODUCER");
19+
Thread consumer = new Consumer(buffer, maxSize, "CONSUMER");
20+
producer.start();
21+
consumer.start();
22+
}
23+
}
24+
/**
25+
* Producer Thread will keep producing values for Consumer
26+
* to consumer. It will use wait() method when Queue is full
27+
* and use notify() method to send notification to Consumer
28+
* Thread.
29+
*/
30+
class Producer extends Thread {
31+
private Queue<Integer> queue;
32+
private int maxSize;
33+
34+
public Producer(Queue<Integer> queue, int maxSize, String name){
35+
super(name);
36+
this.queue = queue;
37+
this.maxSize = maxSize;
38+
}
39+
@Override
40+
public void run() {
41+
while (true){
42+
synchronized (queue) {
43+
while (queue.size() == maxSize) {
44+
try {
45+
System.out .println("队列满, " + "Producer thread waiting for " + "consumer to take something from queue");
46+
queue.wait();
47+
} catch (Exception ex) {
48+
ex.printStackTrace(); }
49+
}
50+
Random random = new Random();
51+
int i = random.nextInt();
52+
System.out.println("Producing value : " + i); queue.add(i); queue.notifyAll();
53+
}
54+
}
55+
}
56+
}
57+
/**
58+
* Consumer Thread will consumer values form shared queue.
59+
* It will also use wait() method to wait if queue is
60+
* empty. It will also use notify method to send
61+
* notification to producer thread after consuming values
62+
* from queue.
63+
*
64+
*/
65+
class Consumer extends Thread {
66+
private Queue<Integer> queue;
67+
private int maxSize;
68+
69+
public Consumer(Queue<Integer> queue, int maxSize, String name){
70+
super(name);
71+
this.queue = queue;
72+
this.maxSize = maxSize;
73+
}
74+
@Override
75+
public void run() {
76+
while (true) {
77+
synchronized (queue) {
78+
while (queue.isEmpty()) {
79+
System.out.println("Queue is empty," + "Consumer thread is waiting" + " for producer thread to put something in queue");
80+
try {
81+
queue.wait();
82+
} catch (Exception ex) {
83+
ex.printStackTrace();
84+
}
85+
}
86+
System.out.println("Consuming value : " + queue.remove()); queue.notifyAll();
87+
}
88+
}
89+
}
90+
}

0 commit comments

Comments
 (0)