这个模式是每发来一个请求就分配一个线程,让这个线程去执行工作。委托消息的一端与执行消息的一端是不同的线程。示例中Host类是一个接受请求并构造和启动线程的类。
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(){ //每次创建一个线程来执行helper的handle方法
public void run(){
helper.handle(count,c);
}
}.start();
System.out.println(" request("+count+","+c+") End");
}
}
public class Helper { //注意:没有继承Thread
public void handle(int count,char c){
System.out.println(" handle("+count+","+c+") Begin");
for(int i=0;i<count;i++){
try {
slowly();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(c);
}
System.out.println("");
System.out.println(" handle("+count+","+c+") End");
}
private void slowly() throws InterruptedException {
Thread.sleep(100);
}
}
public class Main {
public static void main(String[] args){
System.out.println("Main Begins");
Host host=new Host();
host.request(10, 'A');
host.request(20, 'B');
host.request(30, 'C');
System.out.println("Main Ends");
}
}
执行结果:
Main Begins
request(10,A) Begin
request(10,A) End
request(20,B) Begin
handle(10,A) Begin
request(20,B) End
request(30,C) Begin
handle(20,B) Begin
request(30,C) End
Main Ends
handle(30,C) Begin
BCABCACABBCACABCABCABCABACBAC
handle(10,A) End
BBCCBCBCBCBCBCBCBCBBC
handle(20,B) End
CCCCCCCCCC
handle(30,C) End
这种模式中,首先request方法是不需要返回值的,如果需要返回值,参考Future Pattern。
他通过调用方法以及启动线程来传递消息的。这种模式可以应用在服务器的制作上,首先客户端发送一个请求,有主线程来接受,主线程把具体的请求给别的线程执行,而自己继续等待其他客户端的请求。
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Service {
private Service(){}
public static void serve(Socket s) throws IOException, InterruptedException{
DataOutputStream out=new DataOutputStream(s.getOutputStream());
out.writeBytes("HTTP/1.0 200 OK \r\n");
out.writeBytes("Content-type:text/html\r\n");
out.writeBytes("\r\n");
out.writeBytes("<html><head><title>CountDown</title></head><body>");
out.writeBytes("<h1>Countdown start</h1>");
for(int i=10;i>=0;i--){
out.writeBytes("<h2>"+i+"</h2>");
out.flush();
Thread.sleep(1000);
}
out.writeBytes("</body></html>");
s.close();
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MiniServer {
private int portnumber;//端口号
public MiniServer(int portnumber){
this.portnumber=portnumber;
}
public void execute() throws IOException, InterruptedException{
ServerSocket server=new ServerSocket(portnumber);
while(true){
Socket s=server.accept();
System.out.println("connected to "+s);
Service.serve(s);
}
}
}
import java.io.IOException;
public class Main {
public static void main(String[] arg) throws IOException, InterruptedException{
new MiniServer(8888).execute();
}
}
在浏览器中输入:http://127.0.0.1:8888/执行