Elsewhere there are things that we all miss, yet it takes just one to notice...

Java Thread Pool

Okay, so you want to try out thread pools?
Here’s what they do:

  1. Set the number of parallel operations you wish to allow simultaneously. ie. Dual core you want only 2 threads max running.
  2. Split up some math intense stuff into blocks. ie, building 3d meshes or processing sections of an image.

This test is two files which you can copy and paste into your editor and run.
ThreadPoolTest.java

package threadpooltest;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolTest {

    public static void main(String[] args) {
        ThreadPoolExecutor executor;
        // sets the max threads to run at the same time while others added
        // to the queue will have to wait their turn
        executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        
        // add some threads to the queue and name them so it's outputted
        for (int i = 0; i <= 8; i++)
        {
            WorkerTest task = new WorkerTest("Task " + i);
            System.out.println("A new task has been added : " + task.getName());
            executor.execute(task);
        }
        
        // you can see this deliberate pause to show main thread running
        System.out.println("Main thread sleeping");
        try { Thread.sleep(8000); } 
        catch (InterruptedException ex) {}
        System.out.println("Finished sleeping");
        
        // add a few more
        for (int i = 0; i <= 10; i++)
        {
            WorkerTest task = new WorkerTest("Task " + (i + 5));
            System.out.println("A new task has been added : " + task.getName());
            executor.execute(task);
        }
        
        System.out.println("WAITING FOR TASKS TO FINISH");
        
        // wait for all threads in the queue to complete
        try { executor.awaitTermination(1, TimeUnit.DAYS); } 
        catch (InterruptedException ex) {}
        
        System.out.println("FINISHED");
        
        executor.shutdown();
    }
    
}

WorkerTest.java

package threadpooltest;

import java.util.concurrent.TimeUnit;

/**
 *
 * @author wlgfx
 */
public class WorkerTest implements Runnable {

    private String name;
    
    public WorkerTest(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    @Override
    public void run() {
        try
        {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Start Task: " + name);
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Finished Task: " + name);
        }
        catch (InterruptedException e) {}
    }
    
}
Scroll to top