Thread-per-Message 这个工作交给你了

Per是“每一”的意思,所以thread per message解释过来就是“每个消息一个线程”,message在这里可以看做是“命令”或“请求”的意思,对每隔命令或请求,分配一个线程,有这个线程执行。

使用thread-pre-message模式时,“委托消息的一端”与“执行消息的一端”会是不同的线程,也就像是委托消息的线程,对执行消息的线程说“这个任务交给你了”。

public class ThreadPreMessageTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("main begin!");
        Host host = new Host();
        host.request(1, 'A');
        host.request(2, 'B');
        host.request(3, 'C');
        System.out.println("main end!");
    }
}

class Host{
    private final Helper helper = new Helper();
    public void request(final int count, final char c){
        System.out.println("    request(" + count + ", " + c + ") begin");
        
        new Thread(){
            public void run(){
                helper.handle(count, c);
            }
        }.start();
        
        System.out.println("    request(" +count + ", " + c + ")end");
    }
}

class Helper {
    public void handle(int count, char c) {
        System.out.println("    handle(" + count + ", " + c + ")begin");

        for (int i = 0; i < count; i++) {
            System.out.println(c);
        }

        System.out.println("    handle(" + count + ", " + c + ")end");
    }
}
原文地址:https://www.cnblogs.com/gaotianle/p/3307974.html