前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java并行-6.线程优先级

Java并行-6.线程优先级

作者头像
悠扬前奏
发布2019-05-28 12:37:21
4780
发布2019-05-28 12:37:21
举报
  • 线程可以有自己的优先级,优先级高的线程在竞争资源时会更有优势,但是这不是绝对的。
  • Java线程优先级整型成员变量priority来标识,范围从1到10,数字越大优先级越高。其中有三个静态标量:
代码语言:javascript
复制
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;

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

代码语言:javascript
复制
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();
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.01.19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档