一、定義
指每個message一個線程,message可以了解成“消息”、“指令”或者“請求”。每一個message都會配置設定一個線程,由這個線程執行工作,使用Thread-Per-Message Pattern時,“委托消息的一端”與“執行消息的一端”會是不同的線程。
二、模式案例
該案例中,由Host分發請求,每一個請求分發一個新的線程進行處理。
public class Helper {
public void handle(int count,char c){
System.out.println(" handle("+count+", "+c+") BEGIN");
for(int i=0;i<count;i++){
slowly();
System.out.println(c);
}
System.out.println("");
System.out.println(" handle("+count+", "+c+") END");
}
private void slowly() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public 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");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("main BEGIN");
Host host = new Host();
host.request(10,'A');
host.request(20,'B');
host.request(30,'C');
System.out.println("main END");
}
}

三、模式講解
Thread-Per-Message模式的角色如下:
- Client(委托人)
Client會對Host送出請求(Request)。上述案例中,Client就是Main類。
- Host
Host接收來自Client的請求,然後建立新的線程處理它。
- Helper(幫助者)
Helper實際處理請求。
借鑒學習自https://segmentfault.com/a/1190000015558701