解决线程问题-生产与消费

解决线程问题-生产与消费,第1张

解决线程问题-生产消费
package com.yby7;

class Cleck{
    private int productcount = 0;
    //生产产品
    public synchronized void produceproduct(){
        if (productcount < 20){
            productcount ++;
            System.out.println(Thread.currentThread().getName()+"开始生产第"+productcount+"个产品");
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //消费产品
    public synchronized void consumerproduct(){
        if (productcount > 0){
            System.out.println(Thread.currentThread().getName()+"开始消费第"+productcount+"个产品");
            productcount --;
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//*********************************************************************************
class Producer implements Runnable{//生产者
    private Cleck cleck;

    public Producer(Cleck cleck){
        this.cleck = cleck;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始生产产品...");
        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cleck.produceproduct();
        }
    }
}
//*********************************************************************************
class Customer implements Runnable{//消费者
    private Cleck cleck;
    public Customer(Cleck cleck){
        this.cleck = cleck;
    }
    @Override
    public void run() {

        System.out.println(Thread.currentThread().getName()+"开始消费产品...");

        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cleck.consumerproduct();
        }
    }
}
//*********************************************************************************
public class ProduceTest {
    public static void main(String[] args) {
        Cleck cleck = new Cleck();

        Producer p1 = new Producer(cleck);
        Thread t1 = new Thread(p1);
        t1.setName("生产者1");

        Customer p2 = new Customer(cleck);
        Thread t2 = new Thread(p2);
        t2.setName("消费者1");

        t1.start();
        t2.start();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5660296.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存