MINA(2)Producer Consumer and Encode

本文介绍了线程池的实现原理及其在并发编程中的应用,包括Worker类的实现、线程池类的创建与任务调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MINA(2)Producer Consumer and Encode

1. Producer and Consumer, Threads pool
Threads Pool Example
package com.sillycat.easynio.plugins.mina.threadpool;

public class Worker implements Runnable {

private String cardNumber;

public Worker(String cardNumber) {
this.cardNumber = cardNumber;
}

public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread: " + Thread.currentThread().getName()
+ " do the job " + cardNumber);
}

}

package com.sillycat.easynio.plugins.mina.threadpool;

import java.util.LinkedList;

public class ThreadPool {

private final int nThreads;

private final PoolWorker[] threads;

private final LinkedList<Runnable> queue;

public ThreadPool(int nThreads) {
this.nThreads = nThreads;
queue = new LinkedList<Runnable>();
threads = new PoolWorker[nThreads];
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
}

public void addJob(Runnable r) {
synchronized (queue) {
queue.addLast(r);
queue.notify();
}
}

private class PoolWorker extends Thread {
public void run() {
Runnable r;
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException ignored) {
}
}
r = queue.removeFirst();
}
try {
r.run();
} catch (RuntimeException e) {
}
}
}
}

public int getnThreads() {
return nThreads;
}

}

package com.sillycat.easynio.plugins.mina.threadpool;

public class ThreadPoolTest {

public static void main(String[] args) {
ThreadPool pool = new ThreadPool(20);
pool.addJob(new Worker("050"));
pool.addJob(new Worker("job0110"));
pool.addJob(new Worker("001job"));
}

}

MINA Thread Pool
IoAcceptor
IoConnector
IoProcessor
ExecutorFilter

2. Encode
ProtocolCodecFilter

references:
http://www.iteye.com/topic/1124736
http://www.iteye.com/topic/1125178

http://mina.apache.org


http://www.blogjava.net/mikechen/archive/2012/03/15/371938.html
http://www.iteye.com/topic/1112123
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值