`
chxiaowu
  • 浏览: 235316 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

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

 

 

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

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

分享到:
评论
1 楼 liuyuanhui0301 2013-06-20  

相关推荐

Global site tag (gtag.js) - Google Analytics