写了一个线程池。大家看下哪里有不合理的地方,高手给过滤下,看看是否有不合理的地方,如果可以把其在精悍下。我的设计初衷是这样的。
1.设计一个线程池。大小为10
2.接收数据,如果所有的线程都被占用,则创建零时线程,以备使用。
3.并在处理结束后,销毁零时线程。代码如下package threadPool;
public class SimpleThread extends Thread
{
private boolean runningFlag;//用来记录当前线程的状态
private String argument;//数据
public static int num=0;//当前活动的线程是多少
int nums=0;//记录当前线程的数字。大于10表示非线程线程池的线程
String names="";//记录当前线程的名字
public boolean isRunning()
{
return runningFlag;
}
public synchronized void setRunning(boolean flag)
{
runningFlag = flag;
if (flag)//根据条件唤醒线程
this.notify();
}
public String getArgument()//获取内容。
{return this.argument;}
public void setArgument(String string)//设置
{
argument = string;
}
public SimpleThread(int threadNumber)
{
num++;//让活动线程的数据递增
nums=num;
runningFlag = false;
System.out.println("构造  " + threadNumber + "runningFlag = false;.");
}
public synchronized void run()
{
try{
while (true)
{
System.gc();
if (!runningFlag)
{

this.wait();
} else
{
System.out.println("当前的线程名字是 " + Thread.currentThread().getName()+ "  输入的内容是======" + argument);
names=Thread.currentThread().getName();
 
 sleep(5000);
System.out.println("休息5秒钟后 wait..."+num);
if(nums > 10)return;
 else
 setRunning(false);
}
}
} catch (InterruptedException e)
{
System.out.println("发生异常");
}
}
public void finalize()
{
System.out.println(num+"被释放"+Thread.currentThread().getName()+ names);
  num--;
}
} package threadPool;import java.util.Vector;public class ThreadPoolManager
{
private int maxThread;
public Vector vector;
public void setMaxThread(int threadCount)
{
maxThread = threadCount;
}
public ThreadPoolManager(int threadCount)
{
setMaxThread(threadCount);//设置线程大小
System.out.println("Starting thread pool...");
vector = new Vector();//循环吧将要启动的线程放入vector并启动
for (int i = 1; i <= threadCount; i++)
{
SimpleThread thread = new SimpleThread(i);
vector.addElement(thread);
thread.start();
}
}
public void process(String argument)
{
int i;
for (i = 0; i < vector.size(); i++)
{
SimpleThread currentThread = (SimpleThread) vector.elementAt(i);
if (!currentThread.isRunning())
{
currentThread.setArgument(argument);
currentThread.setRunning(true);
return;
}
}
if (i == vector.size())
{
SimpleThread thread = new SimpleThread(i);
 
thread.start();
thread.setArgument(argument);
thread.setRunning(true);
System.out.println("pool is full, start up temp thread");
}
}
}
package threadPool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestThreadPool
{
public static void main(String[] args)
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String s;
ThreadPoolManager manager = new ThreadPoolManager(10);
while ((s = br.readLine()) != null)
{
 
manager.process(s);
}
} catch (IOException e)
{}
}
}

解决方案 »

  1.   

    写的不错..下..  
            不过貌似现在已经很少人再用 Vector 了..
      

  2.   

    建议用List代替Vector,Vector已经过时。
      

  3.   

    怎么不用java.util.concurrent 下的啊,
    里面的都是线程安全的啊,性能很不错!
      

  4.   

    我想问个问题,还望赐教,
    我知道连接池很有用,也能理解连接池是什么用途,但是对于线程池的用途和用处感觉脑袋很乱,大家能否帮我理一下思路,谢谢.另外如果大家对连接池的代码想看看的话,我这里贴出来:通常商业数据库JDBC驱动都会提供自已的数据库连接池管理器,无需自己制做。
    无论如何,这里给出一个简单实现实现连接池的关键点:
    1. 单实例
    2. 由实现类来管理数据库连接,包括连接,刷新
    3. 重载java.sql.Connection的close功能。当客户程序调用close时不是真正的断开连接,而是将连接归还连接池管理器。
    4. 将数据库属性独立于管理器本身可选:
    1. 实现javax.sql.PooledConnection
    2. 实现javax.sql.DataSource
    3. 实现javax.sql.ConnectionPoolDataSource一个简单实现:
    import java.io.*;
    import java.util.*;
    import java.sql.*;public class ConnectionPool implements Runnable {
        static String configFileName; // 如./connection-pool.properties
        static Properties config;
            private static List list = null;
        private static boolean isCreate = false;
        /**
         * 实现单实例,关键点1
         * @throws SQLException
         */
            public ConnectionPool () throws SQLException {
                    if (list == null) init ();
            if (!isCreate) {
                Thread thread = new Thread(this);
                thread.run();
                isCreate = true;
            }
            }    public synchronized Connection getConnection () {
            if (list == null) return null;        // 寻找空闲的连接
            for (int i = 0; i < list.size(); i ++){
                ConnectionWrap conn = (ConnectionWrap)list.get(i);
                if (conn.free) {
                    conn.free = false;
                    conn.start = System.currentTimeMillis();
                    return conn;
                }
            }        // 没有空闲的连接则自动扩展
            int step = Integer.parseInt(config.getProperty("step"); // 取得自动扩展的步长
            this.addConnection(step);
                return (ConnectionWrap)list.get(list.size() - step - 1);
        }    public void run () {
            long interval = Long.parseLong(config.getProperty("interval"); // 扫描时间
            while (true) {
                try {
                    Thread.sleep(interval);
                } catch (Exception e) {
                    // 出错处理
                }
                scan ();
            }
        }    /**
         * 关键点2,管理连接。一些超时的连接刷新
         */
        private void scan () {
            int timeout = Integer.parseInt(config.getProperty("timeout");
            for (int i = 0; i < list.size(); i ++) {
                ConnectionWrap conn = (ConnectionWrap) list.get(i);
                if (conn.start >; 0) {
                    time = System.currentTimeMillis() - conn.start;
                    if (time >;= timeout)
                        conn.close();
                }
            }        int initCount = Integer.parseInt(config.getProperty("init-count");
            if (list.size() >;  initCount) { // 恢复到初始连接数
                for (int i = list.size() - 1; i >; initCount; i --) {
                    ConnectionWrap conn = (ConnectionWrap) list.get(i);
                    if (conn.free) { // 真正地断开连接
                        try {
                            conn.conn.close();
                        } catch (SQLException ignore){}
                        list.remove(conn);
                    }
                }
            }
        }        private void init () throws SQLException {
                    config = readConfig ();
                    createConnectionPool (config);
            }    /**
         * 读取配置文件
         * @return java.util.Properties
         * @throws SQLException
         */
            private void readConfig () throws SQLException {
                    InputStream in = null;
            try {
                in = new FileInputStream (configFileName);
                config = new Properties ();
                config.load(in);
            } catch (IOException ioe) { // 出错处理
                throw new SQLException (ioe.getMessage());
            } finally {
                if (in != null)
                    try { in.close(); } catch (IOException ignore) {}
            }
            }    private void createConnectionPool () throws SQLException {
            String driverName = config.getProperty("driver-name";        int initCount = Integer.parseInt(config.getProperty("init-count");
            int maxCount = Integer.parseInt(config.getProperty("max-count");
            try {
                Driver driver = Class.forName(driverName);
                addConnection (initCount);
            } catch (Exception e) {
                throw new SQLException (e.getMessage());
            }
        }    private void addConnection (int count) throws SQLException {
            if (list == null) list = new ArrayList (count);
            String url = config.getProperty("url";
            String user = config.getProperty("user";
            String password = config.getProperty("password";        for (int i = 0; i < count; i ++)
                list.add(new ConnectionWrap (url, user, password));
        }    class ConnectionWrap implements Connection {
            Connection conn = null;
            boolean free;
            long start;
            ConnectionWrap (String url, String user, String password) throws Exception {
                Connection conn = DriverManager.getConnection(url, user, password);
                free = true;
            }        /**
             * 这里关键点3,并不真正断开连接,而是归还给管理器
             * @return
             * @throws SQLException
             */
            public boolean close () throws SQLException {
                free = true;
                start = 0;
            }        // 其他java.sql.Connection的方法
            // ...
        }
    }配置文件示例
    driver-name = oracle.jdbc.driver.Driver
    url = jdbcracle:thinhost:1521:employee
    user = scott
    password = tiger
    timeout = 60000 # 一分钟
    init-count = 10
    step = 5
    interval = 1000 # 1秒
    ...以后在客户端可以这么调用
    ConnectionPool pool = new ConnectionPool ();
    Connection conn = null;
    try {
            conn = pool.getConnection ();
    // 其他操作
    } finally {
            if (conn != null) conn.close ();
    }
      

  5.   

    用ThreadPoolExecutor多好呀。
     threadPoolExecutor = new ThreadPoolExecutor(initThreadNum,
                        initThreadNum, _THREAD_KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<Runnable>());