日期:2014-05-20 浏览次数:21051 次
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.util.Date; import java.util.Vector; public class Handler extends Thread { private Vector<Socket> taskQueue; public Handler(Vector<Socket> taskQueue,String threadName) { super(threadName); this.taskQueue = taskQueue; } @Override public void run() { /* * 这里使用一个死循环,保证线程完成它所分配的任务后 * 继续回到线程池中等待分配新的任务 * 从而实现线程重利用 */ while(true){ Socket socket = null; synchronized(taskQueue){ /* * 如果没有排列等候的任务,所有线程一直等待 */ while(taskQueue.isEmpty()){ try { /* * 一个对象调用它的wait()方法时,它会首先释放它的锁 * 然后导致当前线程等待 * 这个时候,等待taskQueue对象的锁 * 的线程会得到锁,进入同步块,运行到这里时,该线程也释放锁,等待。。 * 直到另外一个线程,调用taskQueue.notifyAll()方法, * 所有在这里等待的线程,就会让taskQueue试着去得到它的锁, * 如果得到了锁,才会往下执行。否则一直等待。 */ taskQueue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } /* * 任务队列中出现任务,弹出尾部的任务,保证先进先出顺序 */ socket = taskQueue.remove(taskQueue.size()-1); } try { InputStream in = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String strline = null; while((strline=reader.readLine())!=null){ System.out.println(Thread.currentThread().getName()+" 处理了请求 "+strline); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
------解决方案--------------------
public class WorkRunnable implements Runnable {
private Runnable command;
public WorkRunnable(Runnable command) {
this.command = command;
}
public void run() {
command.run();
}
public void setCommand(Runnable command) {
this.command = command;
}
}
------解决方案--------------------
线程池的话,还是使用现成的 java.util.concurrent.ThreadPoolExecutor 吧,自己要实现的话,你和我都不可能完成!
------解决方案--------------------
public static void main(String[] args) {
int threadMax = 5;
ThreadPoolExecutor executor =
new ThreadPoolExecutor(2,threadMax,3,TimeUnit.SECONDS, new ArrayBlockingQueue(3),new ThreadPoolExecutor.CallerRunsPolicy());
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("请输入:");
final String s = sc.nextLine();
if(threadMax == executor.getActiveCount()){
System.out.println("线程满请稍后输入数据");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else{
executor.execute(new Runnable(){
public void run(){
try {
Thread.sleep(5000);
System.out.println("s:" + s);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}