生产者与消费者
生产者与消费者是典型的多线程的经典案例,在android里的应用有消息队列,handler的massageQueue里面的queueMessage就是消费者专门产生message,消费者就是next方法
package com.ikcsoft.lib;
/**
* Created by Scene Tang on 2020/4/9.
*/
public class TestConsumerProducer {
static void msg(String msg){
System.out.println(msg);
}
public static void main(String [] args){
SyncPerson person = new SyncPerson();
new Thread(new Producer(person, "厂家")).start();
new Thread(new Consumer(person, "客人")).start();
}
public interface Person {
void consume(String personName) throws InterruptedException;
void produce(String personName) throws InterruptedException;
}
public static class Consumer implements Runnable {
private Person person;
private String personName;
public Consumer(Person person, String personName) {
this.person = person;
this.personName = personName;
}
@Override
public void run() {
try {
person.consume(personName);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class Producer implements Runnable {
private Person person;
private String personName;
public Producer(Person person, String personName) {
this.person = person;
this.personName = personName;
}
@Override
public void run() {
try {
person.produce(personName);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class SyncPerson implements Person{
private int bytCount = 0;
public synchronized void produce(String personName) throws InterruptedException {
while (true) {
if (bytCount == 5) {
notifyAll();
msg(personName + "已经生产了足够多的螺丝,等待被消费。。。");
Thread.sleep(1000);
wait();
}
bytCount++;
msg(personName + "生产了" + bytCount + "只螺丝");
Thread.sleep(1000);
}
}
public synchronized void consume(String personName) throws InterruptedException {
while (true) {
if (bytCount == 0) {
notifyAll();
msg(personName + "已将螺丝消费完,需要再生产。。。");
Thread.sleep(1000);
wait();
}
bytCount--;
msg(personName + "消费了" + (5 - bytCount) + "只螺丝");
Thread.sleep(1000);
}
}
}
}