线程的优先级

------------siwuxie095

   

   

   

   

   

   

优先级顺序设置:

   

   

   

如果什么都不设置,则默认为 5

   

   

线程的优先级可以影响线程的执行顺序,但不是绝对

   

   

   

   

代码:

   

package com.siwuxie095.thread;

   

class MyRun implements Runnable{

 

public void run() {

for (int i = 0; i < 5; i++) {

try {

//每打印一次,休眠1

Thread.sleep(1000);

//获取当前线程名称

System.out.println(Thread.currentThread().getName()+"-"+i);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

   

public class ThreadPriority {

   

public static void main(String[] args) {

//创建3个线程对象,传入匿名对象和字符串(标识线程)

Thread t1=new Thread(new MyRun(),"A");

Thread t2=new Thread(new MyRun(),"B");

Thread t3=new Thread(new MyRun(),"C");

 

//设置线程优先级 t1-最小, t2-正常,t3-最大

//优先级越大,或许会提高t3首次执行的速度,即能先抢到CPU资源

//但不是绝对能抢到

t1.setPriority(Thread.MIN_PRIORITY);

t2.setPriority(Thread.NORM_PRIORITY);

t3.setPriority(Thread.MAX_PRIORITY);

 

//启动这3个线程

t1.start();

t2.start();

t3.start();

 

}

   

}

   

   

运行一览:

   

   

   

   

   

   

   

【made by siwuxie095】

原文地址:https://www.cnblogs.com/siwuxie095/p/6629245.html