Thread-Per-Message 的意思是为每一个消息的处理开辟一个线程使得消息能够以并发的方式进行处理,从而提供系统整体的吞吐能力。这就好比电话接线员一样,收到每一个电话投诉或者业务处理请求,都会提交对应的工单,然后交由对应的工作人员来处理。
package concurrent.threadpermessage;
/**
* @className: Request
* @description: 业务请求
* @date: 2022/4/27
* @author: cakin
*/
public class Request {
private final String business;
public Request(String business) {
this.business = business;
}
@Override
public String toString() {
return business;
}
}
package concurrent.threadpermessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* @className: TaskHandler
* @description: 处理每一个提交的 Request
* @date: 2022/4/27
* @author: cakin
*/
public class TaskHandler implements Runnable {
// 需要处理的 Request 请求
private final Request request;
public TaskHandler(Request request) {
this.request = request;
}
@Override
public void run() {
System.out.println("Begin handle " + request);
try {
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End handle " + request);
}
}
package concurrent.threadpermessage;
public class Operator {
public void call(String business) {
TaskHandler taskHandler = new TaskHandler(new Request(business));
new Thread(taskHandler).start();
}
public static void main(String[] args) {
Operator operator = new Operator();
operator.call("银行业务");
operator.call("花园业务");
operator.call("木材业务");
operator.call("学校业务");
operator.call("培训业务");
}
}
Begin handle 木材业务
Begin handle 学校业务
Begin handle 银行业务
Begin handle 花园业务
Begin handle 培训业务
End handle 花园业务
End handle 银行业务
End handle 培训业务
End handle 木材业务
End handle 学校业务
package concurrent.threadpermessage;
import concurrent.threadpool.BasicThreadPool;
import concurrent.threadpool.ThreadPool;
public class Operator1 {
// 使用线程池替代为每一个请求创建线程
private final ThreadPool threadPool = new BasicThreadPool(2, 6, 4, 100);
public void call(String business) {
TaskHandler taskHandler = new TaskHandler(new Request(business));
threadPool.execute(taskHandler);
}
public static void main(String[] args) {
Operator1 operator = new Operator1();
operator.call("银行业务");
operator.call("花园业务");
operator.call("木材业务");
operator.call("学校业务");
operator.call("培训业务");
}
}
Begin handle 银行业务
Begin handle 花园业务
End handle 花园业务
Begin handle 木材业务
End handle 木材业务
Begin handle 学校业务
End handle 银行业务
Begin handle 培训业务
End handle 培训业务
End handle 学校业务
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/124458784
内容来源于网络,如有侵权,请联系作者删除!