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"); }}?
?
适合无需返回值,不要求顺序的。
另外 注意实际执行者得委托给其他类来执行。