首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

JAVA多线程设计方式七 Thread-Per-Message Pattern

2012-06-26 
JAVA多线程设计模式七 Thread-Per-Message Pattern一个线程委托另外一个线程处理。?public class Host {pri

JAVA多线程设计模式七 Thread-Per-Message Pattern

一个线程委托另外一个线程处理。

?

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 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(1000);        } catch (InterruptedException e) {        }    }}

?

?

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

?

?

适合无需返回值,不要求顺序的。

另外 注意实际执行者得委托给其他类来执行。

热点排行