Thread-Per-Message模式 這項工作交給你

定義:

在Thread-Per-Message模式中,消息的委託者和執行者是不同線程的,消息的委託者把消息的交給執行者去執行。

引例

類的一覽表
名字 說明
mian 向host發送 字符顯示請求的類
host 針對請求創建的類
helper 提供字符顯示功能的被動類
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");
    }
}
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.print(c);
        }
        System.out.println("");
        System.out.println("        handle(" + count + ", " + c + ") END");
    }
    private void slowly() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }
}

 

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");
    }
}

main BEGIN
    request(10, A) BEGIN
    request(10, A) END
        handle(10, A) BEGIN
    request(20, B) BEGIN
    request(20, B) END
        handle(20, B) BEGIN
    request(30, C) BEGIN
    request(30, C) END
main END
        handle(30, C) BEGIN
ABCCBACABCABACBBCAACBBCACBAACB
        handle(10, A) END
BCCBBCCBCBBC

Thread-Per-Message模式角色

client:委託人角色向host角色發出請求。

host:host角色收到client角色請求後,會創建並啓動一個線程。先創建的線程使用helper角色處理請求

helper(助手):helper角色爲host角色提供處理功能。

什麼時候使用

適用於操作順序沒有要求

適用於不需要返回值時

適用於服務器

調用方法+啓動線程--發送消息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章