Java多线程(三):线程通信(生产者/消费者)

java多线程(三)

线程通信:生产者/消费者

场景:两个共享固定大小缓冲区线程——即所谓的“生产者”和“消费者”——在实际运行时会发生的问题。生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。

分析:

  1. 对于生产者,没有生产产品前,要通知消费者等待,生产产品后,通知消费者消费。
  2. 对于消费者,消费后,通知生产者生产新的产品消费。

java提供的解决线程通信问题的方法:

  1. wait(), 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁。
  2. notify() ,唤醒一个处于等待状态的线程
  3. notifyAll(), 唤醒同一个对象上所有调用wait()方法的线程,优先级高的线程优先调度
  • 注意:以上方法只能在同步方法或者同步代码块中使用,否则抛出异常,IlleagalMonitorStateException

方案1:管程法

采用并发协作模型:加入“缓冲区”,生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据。

//管程法解决生产者消费者问题
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Consumer(container).start();
    }
}

//生产者
class Productor extends Thread{
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}

//消费者
class Consumer extends Thread{
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    //消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->"+container.pop().id+" 只鸡");
        }
    }
}

//产品对象
class Chicken{
    int id;
    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer{
    //容器大小
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Chicken chicken) {
        //如果容器满了,需要等待消费者消费
        if(count == chickens.length) {
            //通知消费者消费,生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //没有满,需要丢入产品
        chickens[count] = chicken;
        count++;

        //通知消费者消费
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop() {
        //判断能否消费
        if(count == 0) {
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //可以消费
        count--;
        Chicken chicken = chickens[count];

        //吃完了,通知生产者生产
        this.notifyAll();
        return chicken;
    }
}

方案2:信号灯

//生产者消费者方案2:信号灯法,标志位解决
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();

        new Player(tv).start();
        new Wathcer(tv).start();
    }
}

//生产者--->演员
class Player extends Thread{
    TV tv;
    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0) {
                this.tv.play("快乐大本营");
            } else {
                this.tv.play("douyin");
            }
        }
    }
}

//消费者--->观众
class Wathcer extends Thread{
    TV tv;
    public Wathcer(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

//产品 ---> 节目
class TV {
    //演员表演,观众等待 T
    //观众观看,演员等待 F
    String voice; //表演的节目
    boolean flag = true;


    //表演
    public synchronized void play(String voice) {
        if(!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("演员表演了:"+voice);
        //通知观众观看
        this.notifyAll(); //通知唤醒
        this.voice = voice;
        this.flag = !this.flag;
    }

    //观看
    public synchronized void watch() {
        if(flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了:"+voice);
        //通知演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}

线程池

背景:经常创建和销毁使用量特别大的资源,比如并发的线程,对性能影响较大。

思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁

优点:提高响应速度(减少创建新线程时间);降低资源消耗(重复利用线程池中线程);便于线程管理

JDK5.0提供了相关API:ExecutorService 和 Executors

  1. ExecutorService:真正的线程池接口。常见子类:ThreadPoolExecutor

  2. Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池

public class TestPool {
    public static void main(String[] args) {
        //1.创建服务,创建线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        //2.关闭连接
        service.shutdown();
    }
}

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
多线程生产者消费者模式是一种常见的并发编程模式,用于解决生产者消费者之间的数据交互问题。在Java中,可以使用多线程和相关的同步机制来实现生产者消费者模式。 在这种模式中,生产者负责生成数据,并将数据放入共享缓冲区中,而消费者则从缓冲区中取出数据进行处理。为了保证线程安全和避免竞态条件,需要使用锁或其他同步机制来控制对共享缓冲区的访问。 以下是一个简单的Java多线程生产者消费者的示例代码: ```java import java.util.LinkedList; class ProducerConsumer { private LinkedList<Integer> buffer = new LinkedList<>(); private int capacity = 10; public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { while (buffer.size() == capacity) { wait(); } System.out.println("Producer produced: " + value); buffer.add(value++); notify(); Thread.sleep(1000); } } } public void consume() throws InterruptedException { while (true) { synchronized (this) { while (buffer.isEmpty()) { wait(); } int value = buffer.removeFirst(); System.out.println("Consumer consumed: " + value); notify(); Thread.sleep(1000); } } } } public class Main { public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); Thread producerThread = new Thread(() -> { try { pc.produce(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumerThread = new Thread(() -> { try { pc.consume(); } catch (InterruptedException e) { e.printStackTrace(); } }); producerThread.start(); consumerThread.start(); } } ``` 上述代码中,ProducerConsumer类维护了一个缓冲区buffer和一个容量capacity。生产者通过调用produce方法向缓冲区中添加数据,消费者通过调用consume方法从缓冲区中取出数据。在生产者消费者的方法中,使用synchronized关键字来保证同一时间只有一个线程能够访问共享资源,并使用wait和notify方法来实现线程间的通信

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值