Java并行-6.线程优先级

  • 线程可以有自己的优先级,优先级高的线程在竞争资源时会更有优势,但是这不是绝对的。
  • Java线程优先级整型成员变量priority来标识,范围从1到10,数字越大优先级越高。其中有三个静态标量:
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;

以下代码可以展示优先级高的线程倾向于更快完成:

package temp;

public class PriorityDemo {
    public static class HighPriority extends Thread{
        static int count = 0;
        public void run() {
            while(true) {
                synchronized(PriorityDemo.class){
                    count++;
                    if(count > 10000000) {
                        System.out.println("HighPriority is complete!");
                        break;
                    }
                }
            }
        }
    }
    
    public static class LowPriority extends Thread{
        static int count = 0;
        public void run() {
            while(true) {
                synchronized(PriorityDemo.class) {
                    count++;
                    if(count > 10000000) {
                        System.out.println("lowPriority is complete!");
                        break;
                    }
                }
            }
        }
    }
    
    public static void main(String[] args) throws InterruptedException{
        Thread high = new HighPriority();
        LowPriority low = new LowPriority();
        high.setPriority(Thread.MAX_PRIORITY);
        low.setPriority(Thread.MIN_PRIORITY);
        low.start();
        high.start();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容