线程池及其实现

进程,线程是现代操作系统两个比较重要的概念。正是由于它们的存在,使得程序和并发执行得了实现。
通常,创建一个线程的代价远远小于创建一个进程,所以多线程是编写并发程序的首要选择。
然而,即使有多线程,当线程数量太大时,不断的创建线程也会影响系统的性能,这时,我们可以创建
线程池来达到重用线程的目的,从而尽可能有减小开消,从而大大提高系统性能,比如在网络爬虫heritrix
中就使用了线程池。

以下是一个简单线程池的实现(java程序)。

本程序由4个类构成,TestThreadPool,用来测试的类,用来模拟客户端的请求。它会创建20个任务(Task),交给线程
池(ThreadPoolManager)处理。线程池默认维护10个线程,当客户请求一个任务时,它会获取一个空闲线程,然后
处理交给该线程(SimpleThread)处理。

测试线程池的类(TestThreadPool)

ContractedBlock.gif ExpandedBlockStart.gif Code
import java.io.*;
public class TestThreadPool {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        try
               ThreadPoolManager manager 
= new ThreadPoolManager(); //生成线程池
               for(int i=0;i<20;i++)
               {
                   Task t
=new Task("task"+i);
                   manager.ProcessTask(t); 
//处理任务
               }
               }
catch(Exception e)
               {
                   e.printStackTrace();
               } 
            }

}

线程池类(TheadPool)

 

ContractedBlock.gif ExpandedBlockStart.gif Code

import java.util.ArrayList;
public class ThreadPoolManager {
    
private ArrayList threads;  //保存线程
    private int maxThreadCount; //最大的线程数
    
    
public ThreadPoolManager()
    {
        
this(10);
    }
    
public ThreadPoolManager(int maxThreadCount)
    {
        
this.maxThreadCount=maxThreadCount;
        threads
=new ArrayList();
        
for(int i=0;i<maxThreadCount;i++)
        {
            SimpleThread thread
=new SimpleThread(i);
            threads.add(thread);
            thread.start();
        }
        System.out.println(
"thread pool created");
    }
    
//处理一个任务
    public void ProcessTask(Task task)
    {
        SimpleThread thread
=getIdleThread(); //获取一个空闲线程
        if(thread!=null)
        {
            thread.setArgument(task);
            thread.setRunningFlag(
true);
        }
        
else
        {
            System.out.println(
"没有空闲线程!");
        }
    }
    
//获取一个空闲线程
    private synchronized SimpleThread getIdleThread()
    {
        
for(int i=0;i<maxThreadCount;i++)
        {
            SimpleThread thread
=(SimpleThread)threads.get(i);
            
if(!thread.isRunning())
            {
                
return thread;
            }
        }
        
return null;
    }
}

线程类(SimpleThread)

 

ContractedBlock.gif ExpandedBlockStart.gif Code
public class SimpleThread extends Thread {
    
private boolean runningFlag; //线程状态
    private Task argument;  //一个任务
    public SimpleThread(int num)
    {
        
this.runningFlag=false;
        System.out.println(
"thread "+num+" starting");
    }
    
//线程执行
    public synchronized void run()
    {
        
try {
            
while(true)
            {
                
if (!runningFlag) 
                {
                    
this.wait(); //睡眠
                } else 
                {
                    System.out.println(
"processing " + argument.toString());
                    sleep(
3000); //阻塞3秒
                    System.out.println(argument.toString() + " processed");
                    setRunningFlag(
false);
                }
            }
        } 
catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
    }
    
public boolean isRunning()
    {
        
return runningFlag;
    }
    
    
public synchronized void setRunningFlag(boolean flag)
    {
        
this.runningFlag=flag;
        
if(runningFlag)
        {
            
this.notify(); //唤醒线程
        }
    }
    
    
public void setArgument(Task arg)
    {
        
this.argument=arg;
    }

    
public Task getArgument() {
        
return argument;
    }
}

任务类(Task)

 

ContractedBlock.gif ExpandedBlockStart.gif Code
public class Task {
    
private String name; //任务名称
    public Task(String name)
    {
        
this.name=name;
    }
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    
public String toString()
    {
        
return this.name;
    }
}

 

运行结果如下:

thread 0 starting
thread 1 starting
thread 2 starting
thread 3 starting
thread 4 starting
thread 5 starting
thread 6 starting
thread 7 starting
thread 8 starting
thread 9 starting
thread pool created
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
没有空闲线程!
processing task1
processing task3
processing task5
processing task7
processing task9
processing task0
processing task2
processing task4
processing task6
processing task8
task1 processed
task9 processed
task5 processed
task7 processed
task3 processed
task6 processed
task4 processed
task2 processed
task0 processed
task8 processed

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值