代码先锋网 代码片段及技术文章聚合

多线程处理耗时任务的封装方式

技术标签: 多线程

 

工作中用到的处理多任务的多线程实现,以下仅为简略书写以便备忘、

 

package need.most.time.producer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import need.most.time.ProcessorWorkerThread;

public class ProcessingThreadsDispatcher {
	protected int maxQueueSize = new Long(Runtime.getRuntime().maxMemory() / 400000L).intValue();
	int def_pool_size = 100;
	private String defPluginsThreadsPool = "default-threads-pool";
     //这里用一个map来封装,也就是可能有多种处理耗时任务的processor处理器,每一个处理器对应一个处理线程沲也就最合理
	private Map<String, ProcessingThreads<ProcessorWorkerThread>> workerThreads = new ConcurrentHashMap<String, ProcessingThreads<ProcessorWorkerThread>>(32);
	
	ProcessorWorkerThread worker;
	ProcessingThreads<ProcessorWorkerThread> pt;
	{
		worker = new ProcessorWorkerThread();
		pt = new ProcessingThreads<ProcessorWorkerThread>(worker, def_pool_size, maxQueueSize, defPluginsThreadsPool);
		workerThreads.put(defPluginsThreadsPool, pt);
	}
	
	
	//主要的方法入口
	private void walk(final Object arg) {
		//processor 为处理器,专处理耗时任务
		Object processor = new Object();
        String processorId=defPluginsThreadsPool;//应该每一个processor都提供一个唯一的name,这样就可以得到相对应processor
		ProcessingThreads<ProcessorWorkerThread> pt = workerThreads.get(processorId);

		if (pt == null) {
			pt = workerThreads.get(defPluginsThreadsPool);
		}
		if (pt.addItem(processor,arg)) {
			//记录哪个处理器处理的哪个对象等
		}
		
	}
}

 

 

 

package need.most.time;

// 通用的处理器实现
public class ProcessorWorkerThread extends WorkerThread {

	//一般这里就会执行真实代表的处理器实现方法
	@Override
	public void process(QueueItem item) {
		
		Object processor=item.getProcessor();
		Object arg=item.getArg();
		//processor拿着arg对象进行处理耗时任务。
		//processor.process(...)
		System.out.println("do finish");
	}

	@Override
	public WorkerThread getNewInstance() {
		ProcessorWorkerThread worker = new ProcessorWorkerThread();
		return worker;
	}

}

 

 

package need.most.time;

import java.util.concurrent.LinkedBlockingQueue;
//线程处理抽象类
public abstract class WorkerThread extends Thread {

	private LinkedBlockingQueue<QueueItem> queue = null;
	private boolean stopped = false;

	public abstract void process(QueueItem item);
	public abstract WorkerThread getNewInstance();
	public boolean offer(QueueItem item) {
		return queue.offer(item);
	}
	
	public void setQueueMaxSize(int maxSize) {
		LinkedBlockingQueue<QueueItem> oldQueue = queue;

		queue = new LinkedBlockingQueue<QueueItem>(maxSize);

		if (oldQueue != null) {
			queue.addAll(oldQueue);
		}
	}

	@Override
	public void run() {
		QueueItem item = null;

		while (!stopped) {
			try {
				item = queue.take();

				long start = System.currentTimeMillis();

				process(item);

				long end = System.currentTimeMillis() - start;
				System.out.println("do time=" + (end - start) + "ms");
			} catch (Exception e) {
			}

		}

	}
	
	
	

}

 

 

 

 

package need.most.time.producer;

import java.util.ArrayList;

import need.most.time.QueueItem;
import need.most.time.WorkerThread;
//处理线程沲类,些类维护多条处理线程
public class ProcessingThreads<E extends WorkerThread> {
	private int numWorkerThreads = 1;
	private ArrayList<E> workerThreads = null;
	private String name = null;

	public ProcessingThreads(E worker, int numWorkerThreads, int maxQueueSize, String name) {
		this.numWorkerThreads = numWorkerThreads;
		this.workerThreads = new ArrayList<E>(numWorkerThreads);
		this.name = name;
		// 生成指定数量的工作线程
		for (int j = 0; j < numWorkerThreads; j++) {
			WorkerThread t = worker.getNewInstance();

			t.setQueueMaxSize(maxQueueSize);
			t.setDaemon(true);
			t.setName(name + " Queue Worker " + j);
			t.start();
			workerThreads.add((E) t);
		}
	}

	public boolean addItem(Object processor, Object arg) {
		boolean ret = false;
		QueueItem item = new QueueItem(processor, arg);
		//这里应该指定哪一个用户他的唯一标识,这样可以每次处理同一个用户都是由同一个线程来执行
		ret = workerThreads.get(Math.abs(processor.hashCode()) % numWorkerThreads).offer(item);
		return ret;
	}

}

 

 

 

 

 

 

package need.most.time;
//封装一些处理参数bean
public class QueueItem {
	private Object arg;
	private Object processor;
	public QueueItem(Object arg, Object processor) {
		super();
		this.arg = arg;
		this.processor = processor;
	}
	public Object getArg() {
		return arg;
	}
	public void setArg(Object arg) {
		this.arg = arg;
	}
	public Object getProcessor() {
		return processor;
	}
	public void setProcessor(Object processor) {
		this.processor = processor;
	}
	

}

 

 

版权声明:本文为u013934901原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013934901/article/details/84709336

智能推荐

多线程处理耗时的业务逻辑

上传sftp大量数据,造成页面假死,用户体验不好 使用多线程,页面显示成功,后台让他慢慢上传.有问题留言, //定义线程池 public static ExecutorService tmasCsggpool = Executors.newFixedThreadPool(1);//线程 线程类,耗时的业务逻辑抽取放到这里....

线程池、Handler、HandlerThread 执行耗时任务的Demo

1. 线程池、Handler、HandlerThread 执行耗时任务的Demo Executors.newFixedThreadPool(8): 定长线程池 Executors.newSingleThreadScheduledExecutor(): 单线程的定时任务调度线程池,支持定时以及周期性执行任务 Handler 默认Loop为Main,故主要为其他线程与主线程通讯,例如某线程执行完耗时任...

Netty案例(二)之耗时任务的处理

文章目录 netty版本 Netty耗时任务的处理 代码案例 `Handler`自定义业务线程池 Context中添加线程池 netty版本 使用的netty版本是io.netty:netty-all:4.1.33.Final Netty耗时任务的处理 Netty中EventLoop用来处理IO线程,因此handler中的耗时任务(比如数据库连接、远程调用等)不能在EventLoop里面执行。如果...

87、android处理耗时任务

https://www.jianshu.com/p/e8cc603b8466 1、AsyncTask https://blog.csdn.net/qq_31384551/article/details/90407003 优缺点: 处理单个异步任务简单,可以获取到异步任务的进度 可以通过cancel方法取消还没执行完的AsyncTask 处理多个异步任务代码显得较多 适用:1. 单个异步任务的处理 ...

猜你喜欢

flask框架异步处理耗时任务

flask框架异步处理耗时任务...

多线程处理耗时操作

多线程处理耗时操作的demo。耗时操作包括DB查询和请求接口。   ...

python_Django中的异步任务,处理耗时任务celery

1.Celery介绍 点击查看Celery参考文档 Celery是一个功能完备即插即用的任务队列 Celery适用异步处理问题,比如发送邮件、文件上传,图像处理等等比较耗时的操作,我们可将其异步执行,这样用户不需要等待很久,提高用户体验 2.Celery特点: 简单,易于使用和维护,有丰富的文档 高效,单个Celery进程每分钟可以处理数百万个任务 灵活,Celery中几乎每个部分都可以自定义扩展...

flask 主线程返回,新线程来进行耗时任务的执行

项目中遇到需求,前端返回结果,后端进行比较耗时的操作。例如判断某客户ID是否在远程数据库。根据ID查询远程数据库,如果不存在,在前端提示客户不存在;如果存在,则前端提示客户存在,后端将根据客户ID,查询远程数据库的其他表,并将查询到的信息插入到本地数据库。 本来没有想到多线程,只想着如何在return返回给前端信息之后再进行耗时操作,但在后端试了很多方法,都不能实现效果。后面又想到在前端click...

ThreadPoolTaskExecutor 多线程分解执行耗时任务与单线程串行执行简单比较

为什么80%的码农都做不了架构师?>>>    testNoThreadTask  耗时: times : 27996 ms testThreadTask 耗时: times : 15239 ms 转载于:https://my.oschina.net/hotkit/blog/345839...