话不多说,直接上代码。
public class ProductConsume {
public static void main(String[] args) {
MessageQueue queue=new MessageQueue(2);
for (int i=0;i<3;i++){
int id=i;
new Thread("生产者"+i){
@Override
public void run() {
try {
queue.put(new Message(id,"值"+id));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
new Thread("消费者"){
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
Message message=queue.take();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
//消息队列类,实现java线程间通信
class MessageQueue{
//消息队列集合
private LinkedList<Message> list=new LinkedList<Message>();
//容量
private int capacity;
//获取消息
public Message take() throws InterruptedException {
//检查队列是否为空
synchronized (list) {
while (list.isEmpty()){
System.out.println("队列为空,消费者线程等待");
list.wait();
}
//从队列头部返回消息
Message message=list.removeFirst();
list.notifyAll();
System.out.println("已消费消息"+message);
return message;
}
}
//存入消息
public void put(Message message) throws InterruptedException {
synchronized (list){
while (list.size()==capacity){
System.out.println("队列已满,生产者线程等待");
list.wait();
}
//新的消息加到队列尾部
list.addLast(message);
System.out.println("已生产消息"+message);
list.notifyAll();
}
}
public MessageQueue(int capacity) {
this.capacity = capacity;
}
}
final class Message{
private int id;
private Object value;
public Message(int id, Object value) {
this.id = id;
this.value = value;
}
public int getId() {
return id;
}
public Object getValue() {
return value;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", value=" + value +
'}';
}
}