多程线设计模式 -- woker thread pattern
2009-09-17 00:00:00 来源:WEB开发网请求对象
Java代码
public class Request {
private final String name; // 委托者
private final int number; // 请求编号
private static final Random random = new Random();
public Request(String name, int number) {
this.name = name;
this.number = number;
}
public void execute() {
System.out.println(Thread.currentThread().getName() + " executes " + this);
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
}
}
public String toString() {
return "[ Request from " + name + " No." + number + " ]";
}
}
工作线程
Java代码
public class WorkerThread extends Thread {
private final Channel channel;
public WorkerThread(String name, Channel channel) {
super(name);
this.channel = channel;
}
public void run() {
while (true) {
Request request = channel.takeRequest();
request.execute();
}
}
}
放入请求线程
Java代码
public class ClientThread extends Thread {
private final Channel channel;
private static final Random random = new Random();
public ClientThread(String name, Channel channel) {
super(name);
this.channel = channel;
}
public void run() {
try {
for (int i = 0; true; i++) {
Request request = new Request(getName(), i);
channel.putRequest(request);
Thread.sleep(random.nextInt(1000));
}
} catch (InterruptedException e) {
}
}
}
测试类
Java代码
public class Main {
public static void main(String[] args) {
Channel channel = new Channel(5); // 工作线程的數量
channel.startWorkers();
new ClientThread("Alice", channel).start();
new ClientThread("Bobby", channel).start();
new ClientThread("Chris", channel).start();
}
}
1.启动线程是繁重的操作
如果可以把自己的工作交给别人做,自己的可以去做其他事情.线程也一亲.如果可以把工作交给其他线程,自己就可以继续进到下一个工作.这是Thread-Per-Message Pattern 的主题.
2.控制承载量
Worker Thread 还有一个主题.就是承载量的控制.
Worker 参与者的数量可以根据设置大小.
3. invocation(启动方法)与execution(执行方法)分离
提高响应性
控制实行顺序
可取消和可重复执行
分散处理的第一步
更多精彩
赞助商链接