一、休眠(sleep)
影响任务行为的一种简单的方法是调用sleep(),这将使任务终止给定的时间。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SleepingTask extends LiftOff{
public void run() {
while(countDown-->0){
System.out.println(status());
//thread.sleep(100);//旧方法
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.err.println("Interrupt");
}
}
}
public static void main(String[] args) {
ExecutorService exec=Executors.newCachedThreadPool();
for (int i=0;i<5;i++){
exec.execute(new SleepingTask());
}
exec.shutdown();
}
}
二、优先级
线程的优先级将线程的重要性传递给了调度器,尽管CPU处理现有线程集的顺序是不确定的,但是调度器将倾向于让优先级最高的线程先执行。然后这并不意味着优先级较低的得不到执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class SleepingTask extends LiftOff{
public void run() {
while(countDown-->0){
System.out.println(status());
//thread.sleep(100);//旧方法
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.err.println("Interrupt");
}
}
}
public static void main(String[] args) {
ExecutorService exec=Executors.newCachedThreadPool();
for (int i=0;i<5;i++){
exec.execute(new SleepingTask());
}
exec.shutdown();
}
}