多线程的优先级_setPriority()

2017-06-10  本文已影响0人  暖熊熊
package com.ghw.thread;
/**
 * 线程的优先级
 * @author Administrator
 *
 */
class MyRun implements Runnable {

    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

public class ThreadDemo05 {

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRun(), "A");
        Thread t2 = new Thread(new MyRun(), "B");
        Thread t3 = new Thread(new MyRun(), "C");
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.MAX_PRIORITY);
        t3.setPriority(Thread.NORM_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }
}

运行结果:

B:0
C:0
A:0
C:1
B:1
A:1
B:2
A:2
C:2
A:3
C:3
B:3
C:4
A:4
B:4

从运行结果可以看出,线程的执行顺序不一定按照设定的优先级执行,这是因为线程不一定能获得cpu资源。

上一篇 下一篇

猜你喜欢

热点阅读