java并发-生产者消费者模式

Java线程通信与资源管理
本文探讨了Java中线程间的通信机制,包括Object的wait()和notifyAll()方法的使用,以及通过Vector和Semaphore实现生产者-消费者模式。展示了如何使用BlockingQueue简化线程同步,同时引入Semaphore作为另一种资源管理和线程同步的工具。

java并发总结三

实现线程间通信的几种方法

  1. Object.wait(),notifyAll

    package concurrent.Produce_Consumer;
    
    import java.util.Vector;
    import java.util.concurrent.TimeUnit;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class ProducerConsumerSolutionDemoOne {
    
        public static void main(String[] args) {
            Vector sharedQueue = new Vector();
            int size = 4;
            Thread prodThread = new Thread(new ProducerThread(sharedQueue, size), "Producer");
            Thread consThread = new Thread(new ConsumerThread(sharedQueue, size), "Consumer");
    
            prodThread.start();
            consThread.start();
        }
    
    
    }
    
    class ProducerThread implements Runnable {
    
        private final Vector queue;
        private final int SIZE;
    
        public ProducerThread(Vector queue, int size) {
            this.queue = queue;
            this.SIZE = size;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 7; i++) {
                System.out.println(" Produced: " + i);
                try {
                    produce(i);
                } catch (InterruptedException e) {
                    Logger.getLogger(ProducerThread.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        }
    
        public void produce(int i) throws InterruptedException {
            // wait if queue is full
            while (queue.size() == SIZE) {
                synchronized (queue) {
                    System.out.println("queue is full " + Thread.currentThread().getName() + " is waiting,size: " + queue.size());
                    queue.wait();
                }
            }
            // notify consumer take element
            synchronized (queue) {
                queue.add(i);
                queue.notifyAll();
            }
    
        }
    }
    
    class ConsumerThread implements Runnable {
    
        private final Vector queue;
        private final int SIZE;
    
        public ConsumerThread(Vector queue, int size) {
            this.queue = queue;
            this.SIZE = size;
        }
    
        @Override
        public void run() {
            while (true) {
                try {
                    System.out.println("Consumed: " + consume());
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException e) {
                    Logger.getLogger(ConsumerThread.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        }
    
        public int consume() throws InterruptedException {
            //wait if queue isEmpty
            while (queue.isEmpty()) {
                synchronized (queue) {
                    System.out.println("Queue is empty " + Thread.currentThread().getName()
                            + " is waiting , size: " + queue.size());
    
                    queue.wait();
                }
            }
            synchronized (queue) {
                queue.notifyAll();
                return (Integer) queue.remove(0);
            }
        }
    }
    /*
    Queue is empty Consumer is waiting , size: 0
     Produced: 0
     Produced: 1
    Consumed: 0
     Produced: 2
     Produced: 3
     Produced: 4
     Produced: 5
    queue is full Producer is waiting,size: 4
    Consumed: 1
     Produced: 6
    queue is full Producer is waiting,size: 4
    Consumed: 2
    Consumed: 3
    Consumed: 4
    Consumed: 5
    Consumed: 6
    Queue is empty Consumer is waiting , size: 0
    
    */
    
  2. BlockingQueue

    public class ProducerConsumerSolution {
    
        public static void main(String[] args) {
            BlockingQueue<Integer> sharedQ = new LinkedBlockingQueue<Integer>();
            
            Producer p = new Producer(sharedQ);
            Consumer c = new Consumer(sharedQ);
            
            p.start();
            c.start();
        }
    }
    
    class Producer extends Thread {
        private BlockingQueue<Integer> sharedQueue;
    
        public Producer(BlockingQueue<Integer> aQueue) {
            super("PRODUCER");
            this.sharedQueue = aQueue;
        }
    
        public void run() {
            // no synchronization needed
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(getName() + " produced " + i);
                    sharedQueue.put(i);
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    
    class Consumer extends Thread {
        private BlockingQueue<Integer> sharedQueue;
    
        public Consumer(BlockingQueue<Integer> aQueue) {
            super("CONSUMER");
            this.sharedQueue = aQueue;
        }
    
        public void run() {
            try {
                while (true) {
                    Integer item = sharedQueue.take();
                    System.out.println(getName() + " consumed " + item);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    Output
    PRODUCER produced 0
    CONSUMER consumed 0
    PRODUCER produced 1
    CONSUMER consumed 1
    PRODUCER produced 2
    CONSUMER consumed 2
    PRODUCER produced 3
    CONSUMER consumed 3
    PRODUCER produced 4
    CONSUMER consumed 4
    PRODUCER produced 5
    CONSUMER consumed 5
    PRODUCER produced 6
    CONSUMER consumed 6
    PRODUCER produced 7
    CONSUMER consumed 7
    PRODUCER produced 8
    CONSUMER consumed 8
    PRODUCER produced 9
    CONSUMER consumed 9
    */
    
    
  3. Semaphore

  • Semaphore是一个计数信号量。
  • 从概念上将,Semaphore包含一组许可证。
  • 如果有需要的话,每个acquire()方法都会阻塞,直到获取一个可用的许可证。
  • 每个release()方法都会释放持有许可证的线程,并且归还Semaphore一个可用的许可证。
  • 然而,实际上并没有真实的许可证对象供线程使用,Semaphore只是对可用的数量进行管理维护。
package concurrent.Produce_Consumer;

import java.util.Vector;
import java.util.concurrent.Semaphore;

public class ProducerConsumerSolutionDemoTwo {
    public static void main(String[] args) {
        Semaphore notFull = new Semaphore(10);
        Semaphore notEmpty = new Semaphore(0);
        Vector queue = new Vector();
        Producer producer = new Producer("生产者线程", notFull, notEmpty, queue);
        Consumer consumer = new Consumer("消费者线程", notFull, notEmpty, queue);

        producer.start();
        consumer.start();
    }
}

class Producer extends Thread {

    private Semaphore notFull;
    private Semaphore notEmpty;
    //    private Semaphore mutex;
    private Vector queue;
    private final int SIZE = 4;

    //,Semaphore mutex
    public Producer(String name, Semaphore notFull, Semaphore notEmpty, Vector queue) {
        super(name);
        this.notFull = notFull;
        this.notEmpty = notEmpty;
//        this.mutex = mutex;
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 7; i++) {
            try {
                // 非满阻塞
                log(" not full is waiting for permit");
                notFull.acquire();
                log(" acquired a permit");
                log(" add value! ");
//                    mutex.acquire();
                queue.add(i);
                notEmpty.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private void log(String msg) {
        System.out.println(Thread.currentThread().getName() + "  " + msg);
    }

}


class Consumer extends Thread {

    private Semaphore notFull;
    private Semaphore notEmpty;
    //    private Semaphore mutex;
    private Vector queue;
    private final int SIZE = 4;

    //,Semaphore mutex
    public Consumer(String name, Semaphore notFull, Semaphore notEmpty, Vector queue) {
        super(name);
        this.notFull = notFull;
        this.notEmpty = notEmpty;
//        this.mutex = mutex;
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 7; i++) {
            try {
                // 非满阻塞
                log(" not empty is waiting for permit");
                notEmpty.acquire();
                log(" acquired a permit");
                log(" getValue! ");
//                    mutex.acquire();
                log(queue.get(i) + "");
                notFull.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private void log(String msg) {
        System.out.println(Thread.currentThread().getName() + " 消费 " + msg);
    }

}
内容概要:本文系统介绍了算术优化算法(AOA)的基本原理、核心思想及Python实现方法,并通过图像分割的实际案例展示了其应用价值。AOA是一种基于种群的元启发式算法,其核心思想来源于四则运算,利用乘除运算进行全局勘探,加减运算进行局部开发,通过数学优化器加速函数(MOA)和数学优化概率(MOP)动态控制搜索过程,在全局探索与局部开发之间实现平衡。文章详细解析了算法的初始化、勘探与开发阶段的更新策略,并提供了完整的Python代码实现,结合Rastrigin函数进行测试验证。进一步地,以Flask框架搭建前后端分离系统,将AOA应用于图像分割任务,展示了其在实际工程中的可行性与高效性。最后,通过收敛速度、寻优精度等指标评估算法性能,并提出自适应参数调整、模型优化和并行计算等改进策略。; 适合人群:具备一定Python编程基础和优化算法基础知识的高校学生、科研人员及工程技术人员,尤其适合从事人工智能、图像处理、智能优化等领域的从业者;; 使用场景及目标:①理解元启发式算法的设计思想与实现机制;②掌握AOA在函数优化、图像分割等实际问题中的建模与求解方法;③学习如何将优化算法集成到Web系统中实现工程化应用;④为算法性能评估与改进提供实践参考; 阅读建议:建议读者结合代码逐行调试,深入理解算法流程中MOA与MOP的作用机制,尝试在不同测试函数上运行算法以观察性能差异,并可进一步扩展图像分割模块,引入更复杂的预处理或后处理技术以提升分割效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值