线程的优先级将该线程的重要性传递给了调度器。尽管CPU处理现有线程集的顺序是不确定的,但是调度器将倾向于让优先权最高的线程先执行。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimplePriorities implements Runnable{
private int countDown=5;
private volatile double d;
private int priority;
public SimplePriorities(int priority){
this.priority=priority;
}
public String toString() {
return Thread.currentThread()+":"+countDown;
}
public void run(){
Thread.currentThread().setPriority(priority);
while(true){
for(int i=1;i<10000;i++){
d+=(Math.PI+Math.E)/(double)priority;
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();
}
}
}
yield()在各种不同的LiftOff任务之间产生分布良好的处理机制。
所谓后台线程,是指在程序运行的时候在后台提供一种通用服务的线程,并且这种线程并不属于程序中不可或缺的部分。因此,当所有的非后台线程结束时,程序也就终止了,同时会杀死进程中的所有后台线程。反过来说,只要有任何非后台线程还在运行,程序就不会终止。
下面的就是一个非后台线程:
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
public class SimpleDaemons implements Runnable{
public void run(){
try{
while(true){
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread()+" "+this);
}
}catch(InterruptedException e){
System.out.println("sleep() interrupted");
}
}
public static void main(String[] args) throws Exception {
for(int i=0;i<10;i++){
Thread deamon=new Thread(new SimpleDaemons());
deamon.setDaemon(true);
deamon.start();
}
System.out.println("All deamons started");
TimeUnit.MILLISECONDS.sleep(175);
}
}
必须在线程启动之前调用setDaemon()方法,才能把它设置为后台线程。
下面我们来定制线程:
import java.util.concurrent.ThreadFactory;
public class DaemonThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r){
Thread t=new Thread(r);
t.setDaemon(true);
return t;
}
}
这与普通的ThreadFactory的唯一差异就是它将后台状态全部设置为了true。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class DaemonFromFactory implements Runnable{
public void run(){
try{
while(true){
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread()+" "+this);
}
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
public static void main(String[] args) throws Exception {
ExecutorService exec=Executors.newCachedThreadPool(
new DaemonThreadFactory());
for(int i=0;i<10;i++)
exec.execute(new DaemonFromFactory());
System.out.println("All daemons started");
TimeUnit.MILLISECONDS.sleep(500);
}
}
每个静态的ExectorService创建方法都被重载为接收一个ThreadFactory对象,而这个对象江北用来创建新的进程。
原文:http://www.cnblogs.com/daochong/p/4839512.html