zoukankan      html  css  js  c++  java
  • 多线程的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();
        }
    }
  • 相关阅读:
    CodeForces 383C-dfs序-线段树
    poj-3321-dfs序-线段树-邻接表
    poj2528-Mayor's posters-线段树离散化、基础
    hdu3333-Turing Tree-线段树+离线+离散化
    poj 1151-atlantis-线段树扫描线求面积并
    Changes favor the connective minds.
    HDU 4800/zoj 3735 Josephina and RPG 2013 长沙现场赛J题
    HDU 1203 I NEED A OFFER! 01背包
    hdu 1175 连连看 DFS
    Codeforces Round #208 (Div. 2) 358D Dima and Hares
  • 原文地址:https://www.cnblogs.com/zheaven/p/12164222.html
Copyright © 2011-2022 走看看