生产者消费者模式(入门备忘)

本文探讨了并发编程中的核心概念,通过实现一个简单的生产者消费者模型,展示了如何使用同步机制来解决线程间的数据共享问题。通过生产者线程向共享数据堆栈中添加元素,而消费者线程从中移除元素,演示了如何利用同步方法如wait(), notify()等确保数据的一致性和线程的安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.基础类:简单的对num的操作,注意同步
public class SynStackNum {

private int num = 0;

public synchronized void printAdd(String threadName) {
num++;
System.out.println("生产线程: "+ Thread.currentThread().getName()+",threadName="+threadName+", 生产 num ="+num);
}

public synchronized void printDel(String threadName) {
num--;
System.out.println("消费线程: "+Thread.currentThread().getName()+",threadName="+threadName+", 消费 num ="+num);
}


public synchronized int getNum() {
return num;
}

public synchronized void setNum(int num) {
this.num = num;
}
}
2.然后是生产者:
public class ProductThread implements Runnable {
private SynStackNum c;
public String name;

public ProductThread(String name, SynStackNum c) {
this.name = name;
this.c = c;
}

@Override
public void run() {
while (true) {
synchronized (c) {
if (c.getNum() >= 10) {
try {
System.out.println(getClass() + ",数据过多,增加操作 wait...");
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
c.printAdd(name);
c.notify();
System.out.println(this.getClass() + ",增加 notify.........");
try {
// Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

public synchronized SynStackNum getC() {
return c;
}

public synchronized void setC(SynStackNum c) {
this.c = c;
}
}
3.消费者:
package com.my.thread;

public class ComsumThread implements Runnable {
public String name;

private SynStackNum c;

public ComsumThread(String name, SynStackNum c) {
this.name = name;
this.c = c;
}

@Override
public void run() {
while (true) {
synchronized (c) {
try {
// 让当前线程等待,即持有当前对象锁的线程等待
if (c.getNum() <= 1) {
System.out.println(getClass() + ",没有数据,删除操作 wait...");
c.wait();
}
// Thread.sleep(1000);
c.printDel(name);
c.notify();
System.out.println(getClass() + ",删除... notify...........");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

public synchronized SynStackNum getC() {
return c;
}

public synchronized void setC(SynStackNum c) {
this.c = c;
}
}
3.测试主线程:
public class Main {

private SynStackNum c = new SynStackNum();

public static void main(String[] args) {
new Main().start();
}

private void start() {
ComsumThread c1 = new ComsumThread("consum11", c);
ComsumThread c2 = new ComsumThread("consum22", c);
ProductThread p1 = new ProductThread("procdct11", c);
ProductThread p2 = new ProductThread("procdct22",c);

ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(c1);
exec.execute(c2);
exec.execute(p1);
exec.execute(p2);

System.out.println("主线程结束 end..");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值