java multithreading six: two case studies multithreading - production of computers

Article Source https://www.jianshu.com/p/61882b068f6f

Articles corresponding video source: https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

A computer designed production and handling Computers, requirements to produce a computer, a computer to move, if not produced a new computer, the computer is waiting for new porter output; if the computer does not move produced, We will have to wait for the computer to move out of reproduction, and the production of statistics at the computer.
  In this procedure, it is a standard producers and consumers processing model, the following program code specific counties.

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Resource res = new Resource();
        Producer st = new Producer(res);
        Consumer at = new Consumer(res);
        new Thread(at).start();
        new Thread(at).start();
        new Thread(st).start();
        new Thread(st).start();
    }
}
class Producer implements Runnable {
    private Resource resource;
    public Producer(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                this.resource.make();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable {
    private Resource resource;
    public Consumer(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                this.resource.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Resource {
    private Computer computer;
    public synchronized void make() throws InterruptedException {
        while (computer != null) {//已经生产过了
            wait();
        }
        Thread.sleep(100);
        this.computer = new Computer("DELL", 1.1);
        System.out.println("【生产】" + this.computer);
        notifyAll();
    }
    public synchronized void get() throws InterruptedException {
        while (computer == null) {//已经生产过了
            wait();
        }
        Thread.sleep(10);
        System.out.println("【搬运】" + this.computer);
        this.computer = null;
        notifyAll();
    }
}
class Computer {
    private static int count;//表示生产的个数
    private String name;
    private double price;
    public Computer(String name, double price) {
        this.name = name;
        this.price = price;
        this.count++;
    }
    @Override
    public String toString() {
        return "【第" + count + "台电脑】电脑名字:" + this.name + "价值、" + this.price;
    }
}

 

 

Published 52 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/YKWNDY/article/details/104955497