生产者消费者模式

来源:互联网 发布:mac版inode如何上网 编辑:程序博客网 时间:2024/06/15 00:23
class MianBao {public String name;public int id = 1;MianBao(String name, int id) {this.name = name;this.id = id;}boolean flag = false;synchronized void shengChan() {if (flag)try {wait();id++;} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "...生产..." + name + id);flag = true;notify();}synchronized void mai() {if (!flag)try {wait();} catch (InterruptedException e) {e.printStackTrace();}       System.out.println(Thread.currentThread().getName() + "-----------消费---------" + name + id);flag = false;notify();}}class producer implements Runnable { // 定义生产者private MianBao mianbao;producer(MianBao mianbao) {this.mianbao = mianbao;}public void run() {while (true) {mianbao.shengChan();}}}class consumer implements Runnable { // 定义消费者private MianBao mianbao;consumer(MianBao mianbao) {this.mianbao = mianbao;}public void run() {while (true) {mianbao.mai();}}}public class ThreadDemo1 {public static void main(String[] args) {MianBao mianbao = new MianBao("面包", 1);producer pro = new producer(mianbao);consumer con = new consumer(mianbao);Thread t1 = new Thread(pro);Thread t2 = new Thread(con);t1.start();t2.start();}}

0 0
原创粉丝点击