栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

多线程——生产者消费者代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多线程——生产者消费者代码

public class Demo1 {
    public static void main(String[] args) {
        List list = new ArrayList();
        Thread t1 = new Thread(new Producer(list));
        Thread t2 = new Thread(new Consumer(list));

        t1.setName("生产者线程");
        t2.setName("消费者线程");

        t1.start();
        t2.start();
    }
}
//生产者
class Producer implements Runnable {
    List list;
    public Producer(List list){
        this.list = list;
    }
    @Override
    public void run() {
        while (true) {
            synchronized(list){
                System.out.println(Thread.currentThread().getName() +" =>执行");
                if (list.size() > 0) {
                    try {
                        System.out.println(Thread.currentThread().getName() +"生产满了,等待");
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Object object = new Object();
                list.add(object);
                System.out.println(Thread.currentThread().getName() + " -----> 产生" + list.size() + "个");
                list.notify();
            }
        }
    }
}
//消费者
class Consumer implements Runnable {
    List list;
    public Consumer(List list) {
        this.list = list;
    }
    @Override
    public void run() {
        while (true) {
            synchronized(list){
                System.out.println(Thread.currentThread().getName() +" =>执行");
                if (list.size() == 0) {
                    try {
                        System.out.println(Thread.currentThread().getName() +" =>无产品,等待");
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.remove(0);
                
                System.out.println(Thread.currentThread().getName() + " -----> 消费" + (list.size()+1) + "个");
                list.notify();
            }
        }
    }
}

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/358553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号