消息队列
package Thread;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Mycontainer<T> {
private LinkedList<T> list = new LinkedList<>();
final int MAX = 10;
private int count = 0;
Lock lock = new ReentrantLock();
Condition procuder = lock.newCondition();
Condition consumer = lock.newCondition();
public void put(T t) {
lock.lock();
while (list.size() == MAX) {
try {
procuder .await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(t);
count++;
consumer .signalAll();
lock.unlock();
}
public T get() {
lock.lock();
while (list.size() == 0) {
try {
consumer .await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = list.removeFirst();
count--;
procuder .signalAll();
lock.unlock();
return t;
}
public synchronized int getCount() {
return count;
}
public static void main(String[] args) {
Mycontainer<String> mycontainer = new Mycontainer<String>();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 5; j++) {
System.out.println(mycontainer.get());
}
}, "C" + i).start();
}
for (int i = 0; i < 10; i++) {
new Thread(() -> {
for (int j = 0; j < 5; j++) {
mycontainer.put(Thread.currentThread().getName() + " " + j);
}
}, "P" + i).start();
}
}
}
阻塞队列
package Thread;
import java.util.LinkedList;
import java.util.List;
public class BlokedQueue {
private List queue = new LinkedList();
private int limit = 10;
public BlokedQueue(int limit) {
this.limit = limit;
}
public synchronized void enQueue(int item) throws InterruptedException {
while (queue.size() == limit) {
wait();
}
if (queue.size() == 0) {
notifyAll();
}
this.queue.add(item);
}
public synchronized int deQueue() throws InterruptedException {
while (queue.size() == 0) {
wait();
}
if (queue.size() == limit) {
notifyAll();
}
return (int) queue.remove(0);
}
}