• 线程审查生产者和消费者


    采纳JAVA多线程技术,设计和实施符合节目制作商和消费者问题:桶的操作,它的最大容量为12子弹,生产者线程被压入螺纹,它被压入腔室,以保持子弹。消费者线程是线程退出。它在不断射出的子弹从室。

    public class ShengChanZheXiaoFeiZhe {
    
    	public static void main(String[] args) {
    		Container c = new Container();
    		BulletProducer producer = new BulletProducer(c);
    		BulletConcumer consumer = new BulletConcumer(c);
    		Thread t1 = new Thread(producer);
    		Thread t2 = new Thread(consumer);
    		t1.start();
    		t2.start();
    	}
    
    }
    //子弹类,id为序号
    class Bullet{
    	int id;
    	Bullet(int id){
    		this.id = id;
    	}
    	//重写toString方法。便于显示子弹序号。
    	@Override
    	public String toString() {
    		return "第"+id+"个子弹";
    	}
    }
    //装子弹的容器。具备一定空间。含有装子弹和发子弹的同步方法(是一个栈),方法须要推断栈的空和满,并使用等待唤醒机制控制。
    class Container{
    	Bullet[] arr = new Bullet[12];
    	int index = 0;
    	public synchronized void push(Bullet bullet){
    		while(index==arr.length){
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		this.notify();
    		arr[index] = bullet;
    		index++;
    	}
    	public synchronized Bullet pop(){
    		while(index==0){
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		this.notify();
    		index--;
    		return arr[index];
    	}
    }
    //生产者。须要被一个线程运行故实现runnable接口,run方法中初始化子弹容器,不断建立子弹对象并向容器中push,并输出子弹序号。

    class BulletProducer implements Runnable{ Container c = null; public BulletProducer(Container c) { this.c = c; } public void run(){ int i = 0; while(true){ Bullet bullet = new Bullet(++i); c.push(bullet); System.out.println("上膛"+bullet); } } } //消费者,也实现了runnable,建立容器,不断从容器中pop子弹。并输出子弹序号。 class BulletConcumer implements Runnable{ Container c = null; public BulletConcumer(Container c) { this.c = c; } public void run(){ while(true){ Bullet bullet = c.pop(); System.out.println("->->->->->->发射"+bullet); } } }



    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    为什么要用where 1=1?
    idea中.ignore忽略提交文件到Git的使用
    IDEA开发工具使用 git 创建项目、拉取分支、合并分支
    Linux常用命令及Linux系统根目录下各个目录的作用
    Xshell和Xftp的安装与使用教程
    Moco使用简单指导
    这样写会有什么问题呢?
    grunt学习笔记
    基于nginx的WebSocket反向代理
    maven依赖查找方法
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4709848.html
Copyright © 2020-2023  润新知