- 컴퓨터의 생산 멀티 스레딩이 사례 연구 : 자바 여섯 멀티 스레딩

기사 근원 https://www.jianshu.com/p/61882b068f6f

기사 상응하는 비디오 소스 : https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

새 컴퓨터를 생산하지 않을 경우 컴퓨터 설계 생산과 컴퓨터, 이동에 컴퓨터를 생산하기 위해 컴퓨터, 요구 사항을 처리, 컴퓨터가 새로운 포터 출력을 기다리고, 컴퓨터가 생성으로 이동하지 않는 경우, 우리는 재생 밖으로 이동 컴퓨터, 컴퓨터에서 통계의 생산을 위해 기다려야 할 것이다.
  이 절차에서는 표준 생산자와 소비자의 처리 모델, 다음의 프로그램 코드를 특정 군이다.

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;
    }
}

 

 

게시 52 개 원래 기사 · 원 찬양 7 ·은 10000 +를 볼

추천

출처blog.csdn.net/YKWNDY/article/details/104955497