多线程的Thread-Per-Message设计模式

Posted zheaven

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程的Thread-Per-Message设计模式相关的知识,希望对你有一定的参考价值。

思路:一个请求创建一个线程

Message消息体

package com.dwz.concurrency2.chapter16;

public class Message {
    private final String value;

    public Message(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

handler简单版(有几个请求创建一个线程)

package com.dwz.concurrency2.chapter16;
import java.util.Random;
public class MessageHandler { private final static Random random = new Random(System.currentTimeMillis()); public void request(Message message) { new Thread(() -> { String value = message.getValue(); try { Thread.sleep(random.nextInt(1000)); System.out.println("The message will be handle by " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }

handler改进版(使用线程池创建线程)

package com.dwz.concurrency2.chapter16;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MessageHandler {
    private final static Random random = new Random(System.currentTimeMillis());
    
    private final static Executor executor = Executors.newFixedThreadPool(5);
    
    public void request(Message message) {
        executor.execute(() -> {
            String value = message.getValue();
            try {
                Thread.sleep(random.nextInt(1000));
                System.out.println("The message will be handle by " + Thread.currentThread().getName() + " " + value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    
    public void shutdown() {
        ((ExecutorService) executor).shutdown();
    }
}

测试

package com.dwz.concurrency2.chapter16;

import java.util.stream.IntStream;

public class PerThreadClient {
    public static void main(String[] args) {
        final MessageHandler handler = new MessageHandler();
        IntStream.rangeClosed(0, 10).forEach(i -> handler.request(new Message(String.valueOf(i))));
        handler.shutdown();
    }
}

 

以上是关于多线程的Thread-Per-Message设计模式的主要内容,如果未能解决你的问题,请参考以下文章

线程池饥饿问题

并发编程领域的Thread-Per-Message设计模式到底是什么?

Day852.Thread-Per-Message模式 -Java 并发编程实战

Day852.Thread-Per-Message模式 -Java 性能调优实战

多线程设计模式-全面详解(学习总结---从入门到深化)

设计模式-深入单例模式精髓-剖析单例模式适用场景以及多线程问题