您的位置:首页 > 编程语言 > Java开发

java线程池和消息队列的运行流程分析

2017-05-13 22:17 351 查看
1.通过以下代码,向线程池中不断的放入线程任务

public static void main(String[] args) {

for(int i=0;i<100;i++){

new TestDriver().sendMsg( Integer.toString( i ) );

}

//new TestDriver().sendMsg(“发起一条对象” );

}

public void sendMsg( String msg ) {

tpm.addLogMsg( msg + "记录一条日志 " );


}

2:addLogMsg()方法,创建一个线程任务,交给线程池去执行

public void addLogMsg(String msg) {

//将一个线程任务交给线程池去执行

Runnable task = new AccessDBThread(msg);

threadPool.execute(task);

}

3.线程池调用AccessDBThread类的run方法。

4.若加入的任务过多。超过了线程池的服务容量,则看线程池的服务拒绝策略是什么样的。

// 管理数据库访问的线程池

@SuppressWarnings({ “rawtypes”, “unchecked” })

final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,

TimeUnit.SECONDS, new ArrayBlockingQueue(WORK_QUEUE_SIZE), this.handler);

5.自定义的服务拒绝策略:将任务信息放入消息队列中

//一个没有能够被线程池执行的消息,重新放入消息队列中

//A handler for tasks that cannot be executed by a ThreadPoolExecutor.

final RejectedExecutionHandler handler = new RejectedExecutionHandler() {

public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(((AccessDBThread) r).getMsg() + "消息放入队列中重新等待执行");
//将未能处理的消息放入消息缓冲队列中
msgQueue.offer(((AccessDBThread) r).getMsg());
}
};


6.定义一个定时执行的调度线程,定时的去调用一个实现了RUNNABLE接口的方法:accessBufferThread,

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(100);

@SuppressWarnings(“rawtypes”)

final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(accessBufferThread, 0, 1, TimeUnit.SECONDS);

7.检查消息队列是否为空,不为空则将消息取出,交给线程池去处理

// 访问消息缓存的调度线程

// 查看是否有待定请求,如果有,则创建一个新的AccessDBThread,并添加到线程池中

final Runnable accessBufferThread = new Runnable() {

@Override
public void run() {
if (hasMoreAcquire()) {
//取出消息队列的头一个信息
String msg = (String) msgQueue.poll();
//新建任务线程,将消息放入该线程中
Runnable task = new AccessDBThread(msg);
//将线程给线程池执行
threadPool.execute(task);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程池 消息队列