线程生产者与消费者
package com.king.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumer {
public static void main(String[] args) {
Container c = new Container();
for (int i = 0; i <3 ; i++) {
new Thread(new ProducerRunnable(c)).start();
}
new Thread(new ConsumerRunnable(c)).start();
}
}
class Food{
private int id;
private String name;
public Food(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Food{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Container{
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
private int count = 0;
public Food[] food = new Food[8];
public void plus(Food f){
lock.lock();
try{
while (count==food.length)
notFull.await();
food[count] = f;
count++;
notEmpty.signal();
} catch (InterruptedException e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
public Food take(){
lock.lock();
Food f = null;
try {
while (count==0)
notEmpty.await();
count--;
f = food[count];
notFull.signal();
return f;
} catch (InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}
return f;
}
}
class ProducerRunnable implements Runnable{
private Container container;
ProducerRunnable(Container container){
this.container = container;
}
public void run(){
try {
for (int i = 0; i < 20; i++) {
Food f = new Food(i, "Food");
container.plus(f);
System.out.println("生产了:" + f);
Thread.sleep(100);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
class ConsumerRunnable implements Runnable{
private Container container;
ConsumerRunnable(Container container){
this.container = container;
}
public void run(){
try {
for (int i = 0; i < 20; i++) {
Food take = container.take();
System.out.println("消费了:" + take);
Thread.sleep(300);
}
} catch (Exception e){
e.printStackTrace();
}
}
}