Tonight I’ve sussed out the thread pooling in Java. I wanted a way of being able to queue up threads to be run, but I also wanted to allow the execution of so many threads at a time in this pool. I’ve heard about these thread pools but as of yet, not used them. I need something like this for my own project for both the server and the client.
package threadpooltest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ThreadPoolTest {
public static void main(String[] args) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
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);
}
System.out.println("Main thread sleeping");
try { Thread.sleep(8000); }
catch (InterruptedException ex) {}
System.out.println("Finished sleeping");
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);
}
// THIS DOESN'T WORK
//System.out.println("WAITING FOR TASKS TO FINISH");
//try { executor.awaitTermination(1, TimeUnit.DAYS); }
//catch (InterruptedException ex) {}
//System.out.println("FINISHED");
executor.shutdown();
}
}
No proper code snippet plugin yet! Grrr!
Anyway, the above code creates the thread pool which will run a max of 5 threads and queue the rest up. Just what I wanted.
package threadpooltest;
import java.util.concurrent.TimeUnit;
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) {}
}
}
The above is the example thread I was testing this with.
All I need now is to do the same with C++, but I’ve already found a header only project on github that does just that.
More to come…
EDIT:
I’ve also noted that the above works on Android too.
At the moment, I’m not holding my breath to see it this works with GWT.
