java多线程系列之杂谈|第一篇:Thread-Per-Message
含义:将一些额外的操作进行异步处理。
范例程序:Main类委托Host类显示文字。Host启动一个线程来处理这项委托的工作。
顺序图如下:
示例代码:
Host
package pattern.perthread;
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(new Runnable() {
@Override
public void run() {
helper.handle(count,c);
}
}).start();
System.out.println(" request( "+count+","+c+") end");
}
}
Helper
package pattern.perthread;
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 (java.lang.InterruptedException e){
e.printStackTrace();
}
}
}
Main
package pattern.perthread;
public class Main {
public static void main(String[] agrs){
System.out.println("main begin");
Host host=new Host();
host.request(2,'A');
host.request(3,'B');
host.request(5,'C');
System.out.println("main end");
}
}
测试结果:
main begin
request( 2,A) begin
request( 2,A) end
request( 3,B) begin
request( 3,B) end
handle( 2,A) begin
request( 5,C) begin
request( 5,C) end
main end
handle( 3,B) begin
handle( 5,C) begin
C
A
B
A
C
B
handle( 2,A) end
C
B
handle( 3,B) end
C
C
handle( 5,C) end
SUCCESS。