//package com.knownspace.tools; public final class ThreadScheduler extends Thread { /* Implement a simple thread scheduler that forces preemptive scheduling for NORM_PRIORITY threads (i.e. threads of the default priority) even if the JVM this is executing on uses cooperative scheduling. Note: there is a small cost when using this in a JVM that is already preemptive, but it's well worth using it always since you never have to worry about scheduling ever again and the extra cost is very small. */ private final static ThreadScheduler singleton = new ThreadScheduler(); //amount of milliseconds to give to each NORM_PRIORITY thread private int timeSlice; //if a timeSlice isn't specified, use this as the default private final static int DEFAULT_TIMESLICE = 100; //(in milliseconds) //////////////////////////////////////////////////////////////////////// public ThreadScheduler getInstance() { return getInstance(DEFAULT_TIMESLICE); } //////////////////////////////////////////////////////////////////////// public ThreadScheduler getInstance(int timeSlice) { return getInstance(timeSlice, Thread.NORM_PRIORITY + 1); } //////////////////////////////////////////////////////////////////////// public ThreadScheduler getInstance(int timeSlice, int priority) { this.timeSlice = timeSlice; //make sure the given priority is legal if (priority < Thread.MIN_PRIORITY) priority = Thread.MIN_PRIORITY; if (priority > Thread.MAX_PRIORITY) priority = Thread.MAX_PRIORITY; this.setPriority(priority); //if this is ever the only thread left, the JVM should just die this.setDaemon(true); return singleton; } //////////////////////////////////////////////////////////////////////// public void run() { while (true) { //wake up just long enough to reset the current NORM_PRIORITY thread //to the next one in the queue, then go right back to sleep try { sleep(timeSlice); } catch (InterruptedException ignored) {} } } }