生产者与消费者

生产者与消费者

生产者与消费者是典型的多线程的经典案例,在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);
  }
}
}
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容