线程的优先级

阅读:230

目录介绍

  • 01.什么是优先级
  • 02.设置优先级

01.什么是优先级

  • 线程调度程序根据线程优先级来决定每个线程应当何时运行。理论上,优先级高的线程比优先级低的线程会获得更多的CPU时间。但是,线程优先级不能保证线程执行的顺序,而且优先级设置也根据运行平台会有不同的表现

02.设置优先级

  • 设置线程的优先级,需要使用如下方法来设置
    public final void setPriority(int newPriority)
    

  • 参数值 newPriority 指定了线程的优先级,取值必须在 MIN_PRIORITY 和 MAX_PRIORITY 之间,默认取值是 NORM_PRIORITY
    /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;
    
    /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;
    
    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;
    

  • 使用方法如下所示:
    public class MyThread extends Thread {
    
    	private int index;
    
    	public MyThread(int index) {
    		this.index = index;
    	}
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 5; i++) {
    			System.out.println("Index: " + index + "-----" + i);
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    
    }
    

  • 建立三个线程,分别设置不同的优先级
    public class Test {
    
    	public static void main(String[] args) {
    		Thread thread1=new MyThread(1);
    		Thread thread2=new MyThread(2);
    		Thread thread3=new MyThread(3);
    		thread1.setPriority(Thread.MIN_PRIORITY);
    		thread2.setPriority(Thread.NORM_PRIORITY);
    		thread3.setPriority(Thread.MAX_PRIORITY);
    		thread1.start();
    		thread2.start();
    		thread3.start();
    	}
    
    }
    

  • 输出结果为:
    Index: 2-----0
    Index: 1-----0
    Index: 3-----0
    Index: 3-----1
    Index: 1-----1
    Index: 2-----1
    Index: 3-----2
    Index: 1-----2
    Index: 2-----2
    Index: 3-----3
    Index: 1-----3
    Index: 2-----3
    Index: 3-----4
    Index: 2-----4
    Index: 1-----4

赞赏支持


精彩留言

发表评论