java中线程优先级是怎么回事给出一个例子

6.线程优先级

java中线程的优先级用1-10之间的数字表示,数值越大优先级越高,默认的优先级为5。Java中的线程优先级是在Thread类中定义的常量 NORM_PRIORITY : 值为5,MAX_PRIORITY :值为10,MIN_PRIORITY : 值为1,缺省优先级为 NORM_PRIORITY。有关优先级的常用方法有两个:1)final void setPriority(int newp) : 修改线程的当前优先级  2)final int getPriority() : 返回线程的优先级。马克-to-win:线程的优先级不能担保线程的执行次序。优先级高的线程获取CPU执行的几率较大,优先级低的线程也有机会执行。参考http://www.javamex.com/tutorials/threads/priority_what.shtml其中有句:there'd quite possibly be lower-priority threads that barely got any CPU at all, being continually starved by higher-priority threads that needed CPU. So Windows has a fallback mechanism, whereby a thread that hasn't run for a long time is given a temporary priority boost.大致意思:为防止低优先级的线程被饿死,Windows有个抗争的方法, 给低优先级的线程一个优先级的临时提升。。。。。。更多的请大家参考此网站。

例:1.6.1

class ThreadMark_to_win extends Thread {
    static boolean go=true;
    private String s;
    int i;
    public ThreadMark_to_win(String s) {
        this.s = s;
    }
    public void run() {
        while(go){
            System.out.println(s+" 到了  "+i++);
            try {
                this.sleep(1); 
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Thread t1 = new ThreadMark_to_win("线程1");
        Thread t2 = new ThreadMark_to_win("线程2");
        t1.setPriority(1);
        t2.setPriority(10);
        t1.start();
        t2.start();
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ThreadMark_to_win.go=false;
        
    }
}

更多请见:http://www.mark-to-win.com/tutorial/java_6_HigherPriorityFirstWrong.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值