Java 生产者&消费者 —— { }

/**
 * 两个线程协同工作,先生产,再消费
 * 面试题 :
 * sleep 与 wait的区别?
 * sleep:让线程进入休眠状态,让出CPU的时间片,不释放对象监视器的所有权(对象锁)
 * wait:让线程进入等待状态,让出CPU的时间片,并释放对象监视器的所有权,等待其它线程通过notify方法来唤醒
 */
public class ProducterCustomerDemo {
    public static void main(String[] args) {
        Food food = new Food();
        Producter p = new Producter(food);
        Customers c = new Customers(food);
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);
        t1.start();
        t2.start();
    }
}

/**
 * 消费者
 */
class Customers implements Runnable{
    private Food food;
    public Customers(Food food){
        this.food = food;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            food.get();
        }
    }
}

/**
 * 生产者
 */
class Producter implements Runnable{
    private Food food;

    public Producter(Food food){
        this.food = food;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0){
                food.set("锅包肉","酸甜口味,爽");
            }else{
                food.set("佛跳墙","大补,滋阴补阳");
            }
        }
    }
}


/**
 * 食物
 */
class Food{
    private String name;
    private String desc;
    private boolean flag = true; //true表示可以生产,false表示可以消费
    /**
     * 生产产品
     */
    public synchronized void set(String name,String desc){
        //不能生产 flag==false
        if(!flag){
            try {
                this.wait();//线程进入等待状态,释放监视器的所有权(对象锁)
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.setName(name);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setDesc(desc);
        flag = false;
        this.notify();//唤醒等待的线程(随机的其中一个)
    }

    /**
     * 消费产品
     */
    public synchronized void get(){
        //不能消费 flag==true
        if(flag){
            try {
                this.wait();//线程进入等待状态,释放监视器的所有权(对象锁)
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.getName()+"->"+this.getDesc());
        flag = true;
        this.notify();//唤醒等待的线程(随机的其中一个)
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "Food{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }

    public Food(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public Food() {
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个基于Java生产者消费者问题的代码实现,附带GUI界面: ```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class ProducerConsumer extends JFrame implements ActionListener { private final int BUFFER_SIZE = 5; // 缓冲区大小 private final List&lt;Integer&gt; buffer = new ArrayList&lt;&gt;(BUFFER_SIZE); // 缓冲区 private final Object lock = new Object(); // 同步锁对象 private final JLabel bufferLabel = new JLabel(); // 显示缓冲区的标签 private final JTextField producerTextField = new JTextField(8); // 生产者输入框 private final JTextField consumerTextField = new JTextField(8); // 消费者输入框 private final JButton startButton = new JButton(&quot;开始&quot;); // 开始按钮 private final JButton stopButton = new JButton(&quot;停止&quot;); // 停止按钮 private Producer producer; private Consumer consumer; public ProducerConsumer() { setTitle(&quot;生产者消费者问题&quot;); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2, 20, 10)); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); panel.add(new JLabel(&quot;缓冲区:&quot;)); panel.add(bufferLabel); panel.add(new JLabel(&quot;生产者&quot;)); panel.add(producerTextField); panel.add(new JLabel(&quot;消费者&quot;)); panel.add(consumerTextField); startButton.addActionListener(this); stopButton.addActionListener(this); stopButton.setEnabled(false); panel.add(startButton); panel.add(stopButton); setContentPane(panel); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { // 点击开始按钮时,启动生产者消费者线程 producer = new Producer(); consumer = new Consumer(); producer.start(); consumer.start(); startButton.setEnabled(false); stopButton.setEnabled(true); } else if (e.getSource() == stopButton) { // 点击停止按钮时,停止生产者消费者线程 producer.stopThread(); consumer.stopThread(); startButton.setEnabled(true); stopButton.setEnabled(false); } } private void updateBufferLabel() { // 更新缓冲区标签的显示 String bufferText = &quot;&quot;; for (Integer item : buffer) { bufferText += item + &quot; &quot;; } bufferLabel.setText(bufferText); } private class Producer extends Thread { private boolean stop = false; public void stopThread() { stop = true; } @Override public void run() { while (!stop) { synchronized (lock) { // 如果缓冲区已满,则等待 while (buffer.size() == BUFFER_SIZE) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 生产一个随机数,并添加到缓冲区 int item = (int) (Math.random() * 100); buffer.add(item); System.out.println(&quot;生产者生产了:&quot; + item); updateBufferLabel(); // 唤醒一个等待的线程(可能是消费者) lock.notify(); } try { // 线程休眠一段时间,模拟生产过程 Thread.sleep((int) (Math.random() * 2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } private class Consumer extends Thread { private boolean stop = false; public void stopThread() { stop = true; } @Override public void run() { while (!stop) { synchronized (lock) { // 如果缓冲区为空,则等待 while (buffer.size() == 0) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 从缓冲区中取出一个元素,并消费它 int item = buffer.remove(buffer.size() - 1); System.out.println(&quot;消费者消费了:&quot; + item); updateBufferLabel(); // 唤醒一个等待的线程(可能是生产者) lock.notify(); } try { // 线程休眠一段时间,模拟消费过程 Thread.sleep((int) (Math.random() * 2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new ProducerConsumer(); } } ``` 运行该程序,将会显示一个GUI界面,包括一个显示缓冲区的标签、两个输入框(分别用于生产者消费者输入数据)、一个开始按钮和一个停止按钮。点击开始按钮,程序将启动一个生产者线程和一个消费者线程,并开始模拟生产者消费者在缓冲区中的操作;点击停止按钮,程序将停止生产者消费者线程,结束模拟过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微风拂晚霞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值