线程的优先级

来源:互联网 发布:java汽车租赁项目 编辑:程序博客网 时间:2024/06/05 17:03

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

  

  

  

  

  

  

优先级顺序设置:

  

  

  

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

  

  

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

  

  

  

  

代码:

  

package com.siwuxie095.thread;

  

class MyRunimplements Runnable{

 

publicvoid 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 staticvoid 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】

0 0
原创粉丝点击