Thread-Per-Message是为每一个消息的处理开辟一个线程,以并发方式处理,提高系统整体的吞吐量。这种模式再日常开发中非常常见,为了避免线程的频繁创建和销毁,可以使用线程池来代替。
示例代码如下:
public class Request {
private String business;public Request(String business) {
this.business=business;
}
public String toString() {
return this.business;
}
}
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;public class TaskHandler implements Runnable{
private Request request;public TaskHandler(Request request) {
this.request=request;
}private void slowly() {
try {
TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}@Override
public void run() {
System.out.println("Begin handle "+request);
slowly();
System.out.println("End handle "+request);
}}
import org.multithread.threadpool.BaseThreadPool;
import org.multithread.threadpool.ThreadPool;public class Operator {
private final ThreadPool threadPool=new BaseThreadPool(2,6,4,100);public void call(String business) {
TaskHandler taskHandler=new TaskHandler(new Request(business));
threadPool.execute(taskHandler);
}}
public class TPMtest {
public static void main(String[] args) {
Operator op=new Operator();
String root="Root-Request-";
for(int i=0;i<30;i++) {
op.call(root+i);
}
}
}
运行结果:
Begin handle Root-Request-0
Begin handle Root-Request-1
End handle Root-Request-1
Begin handle Root-Request-2
End handle Root-Request-0
Begin handle Root-Request-3
End handle Root-Request-3
Begin handle Root-Request-4
End handle Root-Request-2
Begin handle Root-Request-5
Begin handle Root-Request-6
Begin handle Root-Request-7
End handle Root-Request-7
Begin handle Root-Request-8
End handle Root-Request-4
Begin handle Root-Request-9
End handle Root-Request-6
Begin handle Root-Request-10
End handle Root-Request-5
Begin handle Root-Request-11
End handle Root-Request-8
Begin handle Root-Request-12
Begin handle Root-Request-13
End handle Root-Request-10
Begin handle Root-Request-14
End handle Root-Request-9
Begin handle Root-Request-15
End handle Root-Request-11
Begin handle Root-Request-16
End handle Root-Request-15
Begin handle Root-Request-17
End handle Root-Request-14
Begin handle Root-Request-18
End handle Root-Request-18
Begin handle Root-Request-19
End handle Root-Request-12
Begin handle Root-Request-20
End handle Root-Request-20
Begin handle Root-Request-21
End handle Root-Request-16
Begin handle Root-Request-22
End handle Root-Request-22
Begin handle Root-Request-23
End handle Root-Request-23
Begin handle Root-Request-24
End handle Root-Request-13
Begin handle Root-Request-25
End handle Root-Request-19
Begin handle Root-Request-26
End handle Root-Request-26
Begin handle Root-Request-27
End handle Root-Request-27
Begin handle Root-Request-28
Begin handle Root-Request-29
End handle Root-Request-25
End handle Root-Request-17
End handle Root-Request-21
End handle Root-Request-24
End handle Root-Request-28
End handle Root-Request-29