1、使用BlockingQueue
main.class
public class Solution1006 {
public static void main(String[] args) {
//Creating shared object
BlockingQueue sharedQueue = new LinkedBlockingQueue();
//Creating Producer and Consumer Thread
Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));
//Starting producer and Consumer thread
prodThread.start();
consThread.start();
}
}
Producer.class
public class Producer implements Runnable {
private final BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for(int i=0; i<10; i++){
try {
System.out.println("Produced: " + i);
sharedQueue.put(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
Consumer.class
public class Consumer implements Runnable{
private final BlockingQueue sharedQueue;
public Consumer (BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
while(true){
try {
System.out.println("Consumed: "+ sharedQueue.take());
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
结果:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Produced: 4
Produced: 5
Consumed: 2
Produced: 6
Produced: 7
Consumed: 3
Produced: 8
Produced: 9
Consumed: 4
Consumed: 5
Consumed: 6
Consumed: 7
Consumed: 8
Consumed: 9
2、wait / notifyAll
下面是一个使用wait()的notify()的规范代码模板:
synchronized (sharedObject) { //锁住操作对象
while (condition) { //当某个条件下
sharedObject.wait(); //进入wait
}
// 做了什么事,就可以激活
shareObject.notify();
}
同上,例如生产者生产10次,队列大小为4,代码如下:
public class Main {
public static void main(String[] args){
Queue<Integer> queue = new LinkedList<>();
int maxSize = 4; //容量
Main main = new Main();
new Thread(main.new Producer(maxSize, queue)).start();
new Thread(main.new Consumer(maxSize, queue)).start();
}
class Producer implements Runnable{
private int maxSize;
private final Queue<Integer> queue;//使用fianl只让queue关联一个对象,使synchronized只锁一个对象,而防止有变化
public Producer(int maxSize, Queue<Integer> queue){
this.maxSize = maxSize;
this.queue = queue;
}
@Override
public void run() {
for(int k=0; k<10; k++){
synchronized(queue){
while(queue.size() == maxSize){
try {
System.out.println("Queue is full, Producer is waitting!");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Produce value: " + k);
queue.offer(k);
queue.notifyAll();
}
}
}
}
class Consumer implements Runnable{
private int maxSize;
private final Queue<Integer> queue;
public Consumer(int maxSize, Queue<Integer> queue){
this.maxSize = maxSize;
this.queue = queue;
}
@Override
public void run(){
while(true){
synchronized(queue){
while(queue.isEmpty()){
try {
System.out.println("Queue is empty, Consumer is waitting!");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int x = queue.poll();
System.out.println("Consumer value: " + x);
queue.notifyAll();
}
}
}
}
}
结果:


105

被折叠的 条评论
为什么被折叠?



