Sleeping
A simple way to affect the behavior of your tasks is by calling sleep( ) to cease (block) the execution of that task for a given time.
If you must control the order of execution of tasks, your best bet is to use synchronization controls.
public class SleepingTask extends LiftOff{
public void run(){
try {
while(countDown-- > 0){
System.out.print(status());
// Old-style:
// Thread.sleep(100);
// Java SE5/6-style
TimeUnit.MICROSECONDS.sleep(100);
}
} catch (InterruptedException e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0; i<5; i++)
exec.execute(new SleepingTask());
exec.shutdown();
}
}
PriorityThe priority of a thread conveys the importance of a thread to the scheduler.
However, this doesn’t mean that threads with lower priority aren’t run (so you can’t get deadlocked because of priorities).
Lower-priority threads just tend to run less often.
Trying to manipulate thread priorities is usually a mistake.
Although the JDK has 10 priority levels, this doesn’t map well to many operating systems.
public class SimplePriorities implements Runnable {
private int countDown = 5;
private volatile double d; //No optimization
private int priority;
public SimplePriorities(int priority){
this.priority = priority;
}
public String toString(){
return Thread.currentThread() + ": " + countDown;
}
@Override
public void run() {
Thread.currentThread().setPriority(priority);
while(true){
// An expensive, interruptable operation
for(int i=1; i<10000; i++){
d += (Math.PI + Math.E)/(double)i;
if(i%1000 == 0)
Thread.yield();
}
System.out.println(this);
if(--countDown ==0)
return;
}
}
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0; i<5; i++)
exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
exec.shutdown();
}
}