java notify唤醒原理_多线程(十一)---等待唤醒机制原理

该博客演示了Java中的生产者消费者问题的解决方案,通过wait()和notify()方法实现线程间的通信。生产者线程生产面包,消费者线程消费面包,共享资源计数器控制生产和消费的同步,确保资源的正确使用。
摘要由CSDN通过智能技术生成

//多线程中通信.多个线程都在处于同一资源,但是处理的任务却不一样

//生产者,生产一个面包

//消费者,消费一个面包.

class Res {

private int count = 1;// 面包数量

private String name;

boolean flag;// 定义标记

// 提供了商品的赋值的方法

public synchronized void set(String name){

// 判断标记 true 执行wait.等待,为false.就生产

if(flag){

try {

wait();

} catch (InterruptedException e) {

}

}

this.name = name+"----"+count;

count++;

System.out.println(Thread.currentThread().getName()+"--生产者----"+this.name);

// 生产完毕,将标记改为true

flag = true;

// 唤醒消费者

this.notify();

}

// 提供了商品获取的方法

public synchronized void get(){

if(!flag){

try {

wait();

} catch (InterruptedException e) {

}

}

System.out.println(Thread.currentThread().getName()+"---消费者---"+this.name);

// 将标记改为false

flag = false;

// 唤醒提供者

this.notify();

}

}

/**

* 消费者

*/

class Customer implements Runnable {

private Res r;

Customer(Res r){

this.r = r;

}

public void run(){

while (true) {

r.get();

}

}

}

/**

* 生产者

*/

class producer implements Runnable {

private Res r;

producer(Res r){

this.r = r;

}

public void run(){

while (true) {

r.set("面包");

}

}

}

public class WaitAndNotifyDemo {

public static void main(String[] args) {

// 1.创建线程资源

Res r = new Res();

// 2.创建线程任务

producer p = new producer(r);

Customer c = new Customer(r);

// 3.执行线程

new Thread(p).start();

new Thread(c).start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值