线程优先级由1~10表示,1最低,默认优先级为5
优先级高的线程获得CPU资源的概率大
用代码演示一下
public class MyThread4 implements Runnable {
public void run(){
for (int i = 0; i <= 20; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
public static void main(String[] args) {
Runnable runnable=new MyThread4();
Thread thread=new Thread(runnable,"mythread");
Thread thread1=new Thread(runnable,"mythread1");
//线程调度,设置线程优先级
thread1.setPriority(10);
thread.setPriority(1);
thread.start();
thread1.start();
}
}
线程的休眠:
让线程暂时睡眠指定时长,线程进入阻塞状态
睡眠时间过后线程再进入可运行状态
pubilc static void sleep(long millis)
millis为休眠时长,以毫秒为单位
调用sleep()方法需处理InterrputedException异常
用代码演示一下
* @Description模拟线程休眠的过程
*/
public class Wait {
//s:线程休眠的秒数
public static void bySec(long s){
for (int i=1;i<=s;i++)
System.out.println(i+"秒");
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("********线程开始休眠******");
Wait.bySec(5);
System.out.println("********线程结束休眠******");
}
}