2013-01-22 104 views
1

可有人给我,我们已经创建了自己的线程池类来获取线程更好的手感简单的例子。我不想使用java中的Executor Service。我的意思是任何内置类的线程池。示例有关线程池的JAVA

谢谢

+2

执行程序是Java SE库的一部分。你为什么不想用它们?他们为管理线程提供了更多有用的API。 –

+0

我读过这个部分..它有一个自己的例子,你将不得不处理所有的事情。 http://www.ibm.com/developerworks/library/j-jtp0730/index.html –

回答

6

这似乎是你在找什么。 http://java.dzone.com/news/java-concurrency-thread-pools

public class ThreadPool { 

    private BlockingQueue taskQueue = null; 
    private List<PoolThread> threads = new ArrayList<PoolThread>(); 
    private boolean isStopped = false; 

    public ThreadPool(int noOfThreads, int maxNoOfTasks){ 
    taskQueue = new BlockingQueue(maxNoOfTasks); 

    for(int i=0; i<noOfThreads; i++){ 
     threads.add(new PoolThread(taskQueue)); 
    } 
    for(PoolThread thread : threads){ 
     thread.start(); 
    } 
    } 

    public void synchronized execute(Runnable task){ 
    if(this.isStopped) throw 
     new IllegalStateException("ThreadPool is stopped"); 

    this.taskQueue.enqueue(task); 
    } 

    public synchronized void stop(){ 
    this.isStopped = true; 
    for(PoolThread thread : threads){ 
     thread.stop(); 
    } 
    } 

} 



public class PoolThread extends Thread { 

    private BlockingQueue taskQueue = null; 
    private boolean  isStopped = false; 

    public PoolThread(BlockingQueue queue){ 
    taskQueue = queue; 
    } 

    public void run(){ 
    while(!isStopped()){ 
     try{ 
     Runnable runnable = (Runnable) taskQueue.dequeue(); 
     runnable.run(); 
     } catch(Exception e){ 
     //log or otherwise report exception, 
     //but keep pool thread alive. 
     } 
    } 
    } 

    public synchronized void stop(){ 
    isStopped = true; 
    this.interrupt(); //break pool thread out of dequeue() call. 
    } 

    public synchronized void isStopped(){ 
    return isStopped; 
    } 
} 
+0

谢谢大家... :)其实我想要得到的线程池的感觉。我想知道内部工作如线程如何被选中(等待和通知)并分配任务。 – user1624173