生产者和消费者的实例代码:
//要生产的食物
public class Food{
public String name;
puiblic Food(String name){
this.name = name;
}
@Override
public String toString(){
return "Food [name=" + name + "]";
}
}
//放置食物的桌子(单例)
public class Table{
private Table(){}
private static Table instance = new Table();
public static Table getInstance(){
return instance;
}
//桌子上的食物
public Food food;
}
public class Productor implements Runnable{
@Override
public void run(){
while(true){
synchronized(""){
//首先判断桌子上有没有食物,如果有,不需要生产,没有则生产
if(Table.getInstance().food == null){
//没有食物,生产
Food food = new Food("汉堡");
//将食物放到桌子上
Table.getInstance().food = food;
System.out.println(String.format("生产者【%s】生产了一个【%s】", Thread.currentThread().getName(), food.name));
//通知消费者消费食物
if(Table.getInstance() != null){
"".notifyAll();
}
}else {
//桌子上有食物,不需要生产
try {
"".wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
}
//消费者
public class Consumer implements Runnable{
@Override
public void run(){
while(true){
synchronized(""){
//判断桌子上有没有食物,有就消费,没有则通知生产者生产
if(Table.getInstance().food == null){
//没有食物,通知生产者生产
try {
"".wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}else {
//有食物,进行消费
System.out.println(String.format("消费者【%s】吃了一个【%s】", Thread.currentThread().getName(), Table.getInstance().food.name));
//消费完食物,将桌子上的食物置为空
Table.getInstance().food == null;
//消费完后通知生产者生产食物
if(Table.getInstance().food == null){
"".notifyAll();
}
}
}
}
}
}
public class Program {
public static void main(String[] args){
Productor p = new Productor();
Consumer c = new Consumer();
Thread t1 = new Thread(p,"生产者1");
Thread t2 = new Thread(p,"生产者2");
Thread t3 = new Thread(p,"生产者3");
Thread t4 = new Thread(p,"生产者4");
Thread t5 = new Thread(c,"消费者1");
Thread t6 = new Thread(c,"消费者1");
Thread t7 = new Thread(c,"消费者1");
Thread t8 = new Thread(c,"消费者1");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
t8.start();
}
}