实现一个队列。
队列的应用场景为:
一个生产者线程将int类型的数入列,一个消费者线程将int类型的数出列
1、Consumer.java
package com.week.pv;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 消费者
* @author xingqijiang
*/
public class Consumer implements Runnable {
private Queue<Integer> queue = new LinkedList<Integer>();
public Consumer(Queue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
if (Thread.currentThread().isInterrupted())
break;
int data;
synchronized (queue) {
if (queue.size() == 0) {
queue.wait();
queue.notifyAll();
}
data = queue.poll();
}
System.out.println(
Thread.currentThread().getId() + " 消费了:" + data + " 已出队");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2、Producer.java
package com.week.pv;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class Producer implements Runnable {
private Queue<Integer> queue = new LinkedList<Integer>();
private int length;
public Producer(Queue<Integer> queue, int length) {
this.queue = queue;
this.length = length;
}
@Override
public void run() {
try {
while (true) {
if (Thread.currentThread().isInterrupted())
break;
Random r = new Random();
int temp = r.nextInt(100);
System.out.println(Thread.currentThread().getId() + " 生产了:" + temp);
synchronized (queue) {
if (queue.size() >= length) {
queue.notifyAll();
queue.wait();
} else
queue.add(temp);
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
3、Main.java
package com.week.pv;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 主函数
* @author xingqijiang
*
*/
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();
int length = 5;
Producer p1 = new Producer(queue,length);
Consumer c1 = new Consumer(queue);
ExecutorService service = Executors.newCachedThreadPool();
service.execute(p1);
service.execute(c1);
}
}