Programmer's Blog

Programmer's reference

[java] thread pool example

public class ThreadPool implements Runnable{
   private final LinkedBlockingQueue\<Runnable\> queue;
   private final List\<Thread\> threads;
   private boolean shutdown;

public ThreadPool(int numberOfThreads) {
   queue = new LinkedBlockingQueue\<\>();
   threads = new ArrayList<>();

for (int i=0; i\<numberOfThreads; i++) {
   Thread thread = new Thread(this);
   thread.start();
   threads.add(thread);
   }
}

public void execute(Runnable task) throws InterruptedException {
   queue.put(task);
}

private Runnable consume() throws InterruptedException {
   return queue.take();
}

public void run() {
   try {
       while (!shutdown) {
         Runnable task = this.consume();
         task.run();
       }
   } catch(InterruptedException e) {
 }
   System.out.println(Thread.currentThread().getName() + " shutdown");
 }

public void shutdown() {
   shutdown = true;

   threads.forEach((thread) -\> {
   thread.interrupt();
   });
}

public static void main(String[] args) throws InterruptedException {
    ThreadPool threadPool = new ThreadPool(5);
    Random random = new Random();

    for (int i=0; i\<10; i++) {
        int fi = i;
        threadPool.execute(() -\> {
          try {
             Thread.sleep(random.nextInt(1000));
             System.out.printf("task %d complete\n", fi);
          } catch (InterruptedException e) {
             e.printStackTrace();
          }
        });
    }

    Thread.sleep(3000);
    threadPool.shutdown();
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: