• java多线程计算机流水线模型


    /*设计一个生产电脑和搬运电脑类,要求每生产出一台电脑就搬走一台电脑。
    *没有生产出新的电脑,则搬运工要等待新电脑产出;
    *如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出生产的电脑数量。 
    */
    package Java多线程_01;
    
    class Resource_01{
    	private Computer computer;
    	public synchronized void make() throws Exception{
    		if(this.computer != null) {
    			super.wait();
    		}
    		Thread.sleep(100);
    		this.computer = new Computer("惠普v1000", 11000);
    		System.out.println("【生产电脑】" + this.computer);
    		super.notifyAll();
    	}
    	public synchronized void get() throws Exception{
    		if(this.computer == null) {
    			super.wait();
    		}
    		Thread.sleep(10);
    		System.out.println("【取走电脑】"+this.computer);
    		this.computer = null;
    		super.notifyAll();
    	}
    }
    
    class Computer{
    	private static int count = 0;
    	private String name;
    	private double price;
    	public Computer(String name, double price) {
    		this.name = name;
    		this.price = price;
    		count++;
    	}
    	public String toString() {
    		return "【第"+count+"台电脑】"+"电脑品牌:"+this.name+"、价值:"+this.price;
    	}
    }
    
    class Producer_01 implements Runnable{
    	private Resource_01 resource;
    	public Producer_01(Resource_01 resource) {
    		this.resource = resource;
    	}
    	public void run() {
    		for(int x=0;x<50;x++) {
    			try {
    				this.resource.make();
    			}catch(Exception e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    class Consumer_01 implements Runnable{
    	private Resource_01 resource;
    	public Consumer_01(Resource_01 resource) {
    		this.resource = resource;
    	}
    	public void run() {
    		for(int x=0;x<50;x++) {
    			try {
    				this.resource.get();
    			}catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    public class homework_02 {
    	public static void main(String[] args) {
    		Resource_01 resource = new Resource_01();
    		new Thread(new Producer_01(resource)).start();
    		new Thread(new Consumer_01(resource)).start();
    	}
    }
    

      

  • 相关阅读:
    kettle imestamp : Unable to get timestamp from resultset at index 22
    ImportError: No module named setuptools 解决方案
    Tesseract-OCR
    python截图
    connect to SQL Server in python on centos
    vertica merge 优化
    kettle crontab java: command not found
    Idea 使用maven+tomcat的时候,编译指定的Profile
    Java中Vector和ArrayList的区别
    Docker入门命令
  • 原文地址:https://www.cnblogs.com/sunzhongyu008/p/11150006.html
Copyright © 2020-2023  润新知