一 多线程之间通信
1.1 多线程间通信
wait,notify,notifyall 必须在同一个同步锁,同步代码块中;且必须成对出现。
1.2 synchronized版实现
知识点:多线程之间的通信;
1.代码
package com.ljf.thread.shengchenxiaofei;
/**
* @ClassName: Resources
* @Description: TODO
* @Author: admin
* @Date: 2024/03/17 15:48:15
* @Version: V1.0
**/
public class Resources {
public static int count;
public static boolean flag=false;
}
生产
package com.ljf.thread.shengchenxiaofei;
/**
* @ClassName: Producer
* @Description: TODO
* @Author: admin
* @Date: 2024/03/17 15:53:40
* @Version: V1.0
**/
public class Producer implements Runnable {
private Resources r;
public Producer(Resources r) {
this.r = r;
}
@Override
public void run() {
while(true){
synchronized (r){
while (r.flag) {
try {
// System.out.println("生产者线程:" + Thread.currentThread().getName() + " 开始进行等待....");
r.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
r.count=r.count+1;
System.out.println("生产者线程:"+Thread.currentThread().getName()+" 生产第"+r.count+" 个馒头");
r.flag=true;
r.notifyAll();
}
}
}
}
消费
package com.ljf.thread.shengchenxiaofei;
/**
* @ClassName: Consumer
* @Description: TODO
* @Author: admin
* @Date: 2024/03/17 16:00:18
* @Version: V1.0
**/
public class Consumer implements Runnable{
private Resources r;
public Consumer(Resources r) {
this.r = r;
}
@Override
public void run() {
while (true){
synchronized (r){
while (!r.flag){
// System.out.println("消费者线程:" + Thread.currentThread().getName() + " 开始进行等待....");
try {
r.wait();//放弃执行权,释放锁
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
int count= r.count;
System.out.println("消费者线程:" + Thread.currentThread().getName() + " 消费第"+count+"个馒头");
r.flag=false;
r.notifyAll();
}
}
}
}
测试
package com.ljf.thread.shengchenxiaofei;
/**
* @ClassName: Testpc
* @Description: TODO
* @Author: admin
* @Date: 2024/03/17 16:04:07
* @Version: V1.0
**/
public class Testpc {
public static void main(String args[]){
Resources r=new Resources();
new Thread(new Producer(r),"t1").start();
new Thread(new Producer(r),"t2").start();
new Thread(new Consumer(r),"t3").start();
new Thread(new Consumer(r),"t4").start();
}
}
2.结果

本文详细介绍Java中多线程间的通信机制,包括wait、notify和notifyAll的使用方法,通过生产者消费者模式实例演示了如何在同步锁下实现线程间的等待与唤醒,确保资源的正确生产和消费。
749

被折叠的 条评论
为什么被折叠?



