生产电脑,取走电脑多线程

public class ThreadDemo{
    public static void main(String[] args) {
        Resource res = new Resource();
        new Thread(new Productor(res)).start();
        new Thread(new Consumer(res)).start();
    }
}
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 Resource{
    private Computer computer;
    private boolean flag = true;//true,要生产,不取走,false,不生产,要取走
    public synchronized void product() {
        if(this.flag == false) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.computer = new Computer("华硕笔记本",4998.00);
        System.out.println("生产" + this.computer);
        this.flag = false;
        super.notifyAll();
    }
    public synchronized void get() {
        if(this.flag == true) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("取走" + this.computer);
        this.flag = true;
        super.notifyAll();
    }
}
class Productor implements Runnable{
    private Resource resource;
    public Productor(Resource resource) {
        this.resource = resource;
    }
    public void proC() {
        for(int x = 0;x < 50;x ++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.resource.product();
        }
    }
    @Override
    public void run() {
        this.proC();
    }
}
class Consumer implements Runnable{
    private Resource resource;
    public Consumer(Resource resource) {
        this.resource = resource;
    }
    public void getC() {
        for(int x = 0;x < 50;x ++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.resource.get();
        }
    }
    @Override
    public void run() {
        this.getC();
    }
}

同步锁机制,生产与取走的切换,休眠的限制。

猜你喜欢

转载自blog.csdn.net/qq_27347147/article/details/84786899
今日推荐