线程通信-java

本文通过Java代码展示了生产者消费者模型在处理多线程共享资源时如何进行线程通信,通过`synchronized`、`notifyAll`和`wait`方法实现资源的生产和消费同步。
摘要由CSDN通过智能技术生成

线程通信

当多个线程操作共享多资源时,线程间通过某种方式相互告知自己的状态,以相互协调, 并避免无效的资源争夺。 

线程通信的常见模型(生产者与消费者模型)

生产者线程负责生产数据

消费者线程负责消费生产者生产的数据。

生产者生产完数据应该等待自己,通知消费者,消费者消费完数据也应该等待自己, 再通知生产者生产。 

public class ThreadCommunication {
    public static void main(String[] args) {
         Desk desk = new Desk();


        //生产者线程
        new Thread(()->{
            while (true) {
                desk.put();
            }
        },"厨师1").start();

        new Thread(()->{
            while (true) {
                desk.put();
            }
        },"厨师2").start();

        new Thread(()->{
            while (true) {
                desk.put();
            }
        },"厨师3").start();

        //消费者线程
        new Thread(()->{
            while (true) {
                desk.get();
            }
        },"吃货1").start();

        //消费者线程
        new Thread(()->{
            while (true) {
                desk.get();
            }
        },"吃货2").start();
    }
}
public class Desk {

    private  ArrayList<String> list =  new ArrayList<String>();

    //厨师1 2 3
    public synchronized void  put() {
        try {
            final Thread thread = Thread.currentThread();

            if (list.size() == 0) {
                list.add(thread.getName()+"做的包子");
                System.out.println(thread.getName()+"做了一个包子");
                Thread.sleep(2000);

                //做完了事情,等待自己,让出机器资源, 唤醒别人
            } else {
                //有包子了, 就不做了
                //唤醒别人
                //等待自己
            }
            this.notifyAll();//唤醒别人
            this.wait(); //等待自己
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //吃货1 ,2
    public synchronized void get() {
        try {
            final Thread thread = Thread.currentThread();
            if (list.size() == 1) {
                //有包子了
                System.out.println(thread.getName() + "吃了"+list.get(0));
                list.clear();
                Thread.sleep(1000);
                this.notifyAll();
                this.wait();
            } else {
                //没有包子
                this.notifyAll();
                this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

  • 18
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值