Java 自己实现一个线程池

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
          
   
    private final int nThreads;
    private final PoolWorker[] threads;
    private final BlockingQueue<Runnable> queue;

    public MyThreadPool(int nThreads) {
          
   
        this.nThreads = nThreads;
        queue = new LinkedBlockingQueue<>();
        threads = new PoolWorker[nThreads];

        for (int i = 0; i < nThreads; i++) {
          
   
            threads[i] = new PoolWorker();
            threads[i].start();
        }
    }

    public void execute(Runnable task) {
          
   
        synchronized (queue) {
          
   
            queue.add(task);
            queue.notify();
        }
    }

    public void shutdown() {
          
   
        for (PoolWorker worker : threads) {
          
   
            worker.shutdown();
        }
    }

    private class PoolWorker extends Thread {
          
   
        private boolean running = true;

        public void run() {
          
   
            while (running) {
          
   
                Runnable task = null;

                synchronized (queue) {
          
   
                    while (queue.isEmpty()) {
          
   
                        try {
          
   
                            queue.wait();
                        } catch (InterruptedException e) {
          
   
                            System.out.println("An error occurred while queue is waiting: " + e.getMessage());
                        }
                    }

                    task = queue.poll();
                }

                try {
          
   
                    task.run();
                } catch (RuntimeException e) {
          
   
                    System.out.println("Thread pool is interrupted due to an issue: " + e.getMessage());
                }
            }
        }

        public void shutdown() {
          
   
            running = false;
        }
    }
}

在这个实现中,首先创建了一个任务队列BlockingQueue,用于存储待执行的任务。然后创建了一定数量的工作线程PoolWorker,这些线程不断从任务队列中获取任务并执行。

在执行任务时,如果任务队列中没有任务,则工作线程会调用wait()方法等待新任务的到来。当有新任务加入队列时,工作线程调用notify()方法唤醒其中一个等待线程,并从队列中取出任务执行。

在MyThreadPool中,通过execute()方法将任务添加到任务队列中,而通过shutdown()方法关闭线程池。其中,PoolWorker类继承自Thread类,实现了运行线程和关闭线程的方法。

需要注意的是,这个实现中只是一个简单的线程池,还有很多需要完善的地方,例如线程池大小的动态调整、线程的回收等等。此外,在实际应用中,为了更好的线程安全和性能,建议使用Java中提供的线程池类Executors,而不是自己实现线程池。

经验分享 程序员 微信小程序 职场和发展