博客
关于我
Object Notify&Wait
阅读量:467 次
发布时间:2019-03-06

本文共 2989 字,大约阅读时间需要 9 分钟。

Java多线程生产消费示例

以下是一个使用Java多线程实现的生产者-消费者模型示例,该模型展示了如何在多线程环境中使用wait和notify方法来实现线程同步。

代码概述

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class NotifyWaitTest {
public static void main(String[] args) {
Queue
queue = new LinkedList<>();
Producer p = new Producer(queue);
Consumer c = new Consumer(queue);
p.produce();
c.consume();
}
}

生产者类(Producer)

public class Producer {
private final Queue
queue;
private static final Random r = new Random(50);
public Producer(Queue
queue) {
this.queue = queue;
}
public void produce() {
Thread pt = new Thread(new Runnable() {
@Override
public void run() {
int count = 100;
synchronized (queue) {
while (count > 0) {
int i = r.nextInt();
queue.add(i);
queue.notify();
count--;
}
}
}
});
pt.start();
}
}

消费者类(Consumer)

public class Consumer {
private final Queue
queue;
public Consumer(Queue
queue) {
this.queue = queue;
}
public void consume() {
Thread cm = new Thread(new Runnable() {
@Override
public void run() {
int count = 100;
synchronized (queue) {
try {
while (count > 0) {
if (queue.isEmpty()) {
queue.wait();
}
int i = queue.poll();
System.out.println("Consume " + i);
count--;
}
} catch (InterruptedException ie) {
System.out.println(ie.getMessage());
}
}
}
});
cm.start();
}
}

代码解释

  • 生产者(Producer)类

    • 使用一个Queue来存储生成的随机整数。
    • produce()方法中,创建一个新的线程,运行一个Runnable任务。
    • 在Runnable任务中,使用count循环从100递减到0。
    • 在每次循环中,生成一个随机整数,添加到Queue中,然后调用queue.notify(),通知等待的消费者线程。
    • 最终,生产者线程启动,开始生成和通知数据。
  • 消费者(Consumer)类

    • 使用同样的Queue来存储和消费整数。
    • consume()方法中,创建一个新的线程,运行一个Runnable任务。
    • 在Runnable任务中,使用count循环从100递减到0。
    • 在每次循环中,调用queue.poll(),取出队列中的整数并打印出来。
    • 如果队列为空,则调用queue.wait(),等待直到有数据被生产并通知。
    • 如果线程被中断,捕获异常并打印错误信息。
  • 主方法(main)

    • 创建一个新的LinkedList作为Queue。
    • 创建一个新的Producer实例,并传递Queue。
    • 创建一个新的Consumer实例,并传递相同的Queue。
    • 调用produce()consume()方法,分别启动生产者和消费者线程。
    • 最终,主线程会等待所有子线程完成,程序会退出。
  • 优点和特点

    • 线程安全:使用Queuesynchronized关键字确保了线程安全,避免了数据竞争和加速。
    • 生产通知:生产者线程在每次添加数据后都会调用queue.notify(),唤醒等待的消费者线程。
    • 消费等待:消费者线程在发现队列为空时会调用queue.wait(),直到有数据被生产并通知。
    • 随机性:生产者线程使用Random生成随机数,确保每次生成的数据是随机的。

    运行结果

    • 当程序运行时,生产者线程会不断生成随机整数并添加到Queue中,同时通知消费者线程。
    • 消费者线程会在queue.poll()方法中取出队列中的整数并打印出来,直到所有数据被消费完毕。

    这种设计模式在多线程环境中非常有用,可以应用于资源有限的环境中,确保生产者和消费者能够高效地交换数据。

    转载地址:http://finbz.baihongyu.com/

    你可能感兴趣的文章
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
    查看>>
    org.springframework.beans.factory.BeanDefinitionStoreException
    查看>>
    org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
    查看>>
    org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>