简单的线程池实例代码

一个简单的线程池处理,下面是创建一个线程,创建好后用ThreadPoolPhotoTool.addThreadTask()添加到线程池中执行即可

private static Runnable createParseTask(final DataSource dataSource) {
return new Runnable() {
public void run() {
//TODO thread task
}
};
}

 

package com.catchdata.thread;

import java.util.LinkedList;

/**
 * A thread pool is a group of a limited number of threads that are used to execute tasks.
 */
public class ThreadPool extends ThreadGroup {

    private boolean isAlive;

    private LinkedList taskQueue;

    private int threadID;

    private static int threadPoolID;

    /**
     * Creates a new ThreadPool.
     * @param numThreads
     *            The number of threads in the pool.
     */
    public ThreadPool(int numThreads) {
        super("ThreadPool-" + (threadPoolID++));
        setDaemon(true);

        isAlive = true;

        taskQueue = new LinkedList();
        for (int i = 0; i < numThreads; i++) {
            new PooledThread().start();
        }
    }
    public int getCountOfNotRun(){
        return taskQueue.size();
    }

    /**
     * Requests a new task to run. This method returns immediately, and the task executes on the next available idle
     * thread in this ThreadPool.
     * <p>
     * Tasks start execution in the order they are received.
     * @param task
     *            The task to run. If null, no action is taken.
     * @throws IllegalStateException
     *             if this ThreadPool is already closed.
     */
    public synchronized void runTask(Runnable task) {
        if (!isAlive) {
            throw new IllegalStateException();
        }
        if (task != null) {
            taskQueue.add(task);
            notify();
        }

    }

    protected synchronized Runnable getTask() throws InterruptedException {
        while (taskQueue.size() == 0) {
            if (!isAlive) {
                return null;
            }
            wait();
        }
        return (Runnable) taskQueue.removeFirst();
    }

    /**
     * Closes this ThreadPool and returns immediately. All threads are stopped, and any waiting tasks are not executed.
     * Once a ThreadPool is closed, no more tasks can be run on this ThreadPool.
     */
    public synchronized void close() {
        if (isAlive) {
            isAlive = false;
            taskQueue.clear();
            interrupt();
        }
    }

    /**
     * Closes this ThreadPool and waits for all running threads to finish. Any waiting tasks are executed.
     */
    public void join() {
        // notify all waiting threads that this ThreadPool is no
        // longer alive
        synchronized (this) {
            isAlive = false;
            notifyAll();
        }

        // wait for all threads to finish
        Thread[] threads = new Thread[activeCount()];
        int count = enumerate(threads);
        for (int i = 0; i < count; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException ex) {
            }
        }
    }

    /**
     * A PooledThread is a Thread in a ThreadPool group, designed to run tasks (Runnables).
     */
    private class PooledThread extends Thread {

        public PooledThread() {
            super(ThreadPool.this, "PooledThread-" + (threadID++));
        }

        public void run() {
            while (!isInterrupted()) {

                // get a task to run
                Runnable task = null;
                try {
                    task = getTask();
                } catch (InterruptedException ex) {
                }

                // if getTask() returned null or was interrupted,
                // close this thread by returning.
                if (task == null) {
                    return;
                }

                // run the task, and eat any exceptions it throws
                try {
                    task.run();
                } catch (Throwable t) {
                    uncaughtException(this, t);
                }
            }
        }
    }
}

 

 

 

package com.catchdata.thread.task;

import com.catchdata.thread.ThreadPool;

public class ThreadPoolPhotoTool {

    private static ThreadPool threadPool;

    static {
        // thread count
        int numThreads = 3;
        // create the thread pool
        threadPool = new ThreadPool(numThreads);
    }

    public static void closeThreadPool() {
        // close the pool and wait for all tasks to finish.
        threadPool.join();
    }

    public static void addThreadTask(Runnable r) {
        threadPool.runTask(r);
    }
    public static int getCountOfNotRun(){
        return threadPool.getCountOfNotRun();
    }

}

这是一个基本的线程池实例代码,它可以执行一些简单的任务: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread("Task " + (i + 1)); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("All tasks completed"); } } class WorkerThread implements Runnable { private String taskName; public WorkerThread(String taskName) { this.taskName = taskName; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " Start. Task = " + taskName); processTask(); System.out.println(Thread.currentThread().getName() + " End."); } private void processTask() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString() { return this.taskName; } } ``` 这个例子中,我们创建了一个固定大小的线程池,大小为5个线程。然后我们创建10个任务,每个任务都是一个实现了Runnable接口的WorkerThread对象,并将它们提交到线程池中执行。每个任务都会在一个新的线程中执行,直到所有任务都完成后,我们关闭线程池。 WorkerThread类实现了Runnable接口,并在run()方法中执行了一些任务。在这个例子中,我们简单地让线程休眠2秒钟。当任务完成时,我们打印一条消息来指示任务已经完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值