随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

思路:

和生产者消费者模型一样。

复制代码
public 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 + "\t电脑价格: " + this.price;
    }
}
复制代码

 

复制代码
public class Resource { //操作类
    private Computer computer;
    public synchronized void create(){
        if (this.computer != null){ // 已经生产了电脑,等待取走
            try {
                super.wait();   // 等待取走
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("生产完毕!");
        this.computer = new Computer("ASUS",1000);
        super.notifyAll();
    }
    public synchronized void get(){
        if (this.computer == null){
            try {
                super.wait();   // 等待生产
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(this.computer);
        this.computer = null;   // 已经取走电脑,没有电脑了
        super.notifyAll();
    }

}
复制代码

 

复制代码
public class Producer implements Runnable{  // 生产电脑线程类
    private Resource resource;
    public Producer(Resource resource){
        this.resource = resource;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            this.resource.create();
        }
    }
}
复制代码

 

复制代码
public class Comsumer implements Runnable{  // 取走电脑线程类
    private Resource resource;
    public Comsumer(Resource resource){
        this.resource = resource;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            this.resource.get();
        }
    }
}
复制代码

 

public class Main {
    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(new Producer(resource)).start();
        new Thread(new Comsumer(resource)).start();
    }
}

输出结果:

 

这个操作不用考虑同步等问题,直接使用等待与唤醒机制就行了,一进一出就搞定。

 

posted on   时间完全不够用啊  阅读(92)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示