毕业设计要写给处理并发连接的服务器,但我怕这个服务器太简单了 呵呵
在IBM那里看到一篇文章,《Java 理论与实践:线程池与工作队列》
现在有个疑问的--->
(1)r = (Runnable) queue.removeFirst();得到一个Runnable,之后run(),这相当于也是启动一个线程,如果在服务器启动线程会造成大的消耗,
(2)但是我查了一下资料,说是Runnable接口消耗没有直接创建Thread的大???
(3)要是我现在设计一个服务器,建立一个ServerSocket 之后启动10个线程同步监听accept(),..之后把接收的socket放到一个类(implements Runnable),
(4)呵呵 方案我都没具体想好 大家给点思路(就是提高服务器能力那种,越麻烦越好 呵呵) 多谢
public class WorkQueue
{
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedList queue; public WorkQueue(int nThreads)
{
this.nThreads = nThreads;
queue = new LinkedList();
threads = new PoolWorker[nThreads]; for (int i=0; i<nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
} public void execute(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 = (Runnable) queue.removeFirst();
} // If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run();
}
catch (RuntimeException e) {
// You might want to log something here
}
}
}
}
}
在IBM那里看到一篇文章,《Java 理论与实践:线程池与工作队列》
现在有个疑问的--->
(1)r = (Runnable) queue.removeFirst();得到一个Runnable,之后run(),这相当于也是启动一个线程,如果在服务器启动线程会造成大的消耗,
(2)但是我查了一下资料,说是Runnable接口消耗没有直接创建Thread的大???
(3)要是我现在设计一个服务器,建立一个ServerSocket 之后启动10个线程同步监听accept(),..之后把接收的socket放到一个类(implements Runnable),
(4)呵呵 方案我都没具体想好 大家给点思路(就是提高服务器能力那种,越麻烦越好 呵呵) 多谢
public class WorkQueue
{
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedList queue; public WorkQueue(int nThreads)
{
this.nThreads = nThreads;
queue = new LinkedList();
threads = new PoolWorker[nThreads]; for (int i=0; i<nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
} public void execute(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 = (Runnable) queue.removeFirst();
} // If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run();
}
catch (RuntimeException e) {
// You might want to log something here
}
}
}
}
}
你要想自己写出具有工业强度的代码,没有5,6年的并发编程经验,估计是很难的。
作为毕业设计,你要是能详细地分析一下java.util.concurrent,比你自己去写这样一段程序要有份量的多吧。