线程中常用的方法(续)
线程的调度:
1.CUP时间片
抢占式:高优先级的线程抢占CPU
2. Java的调度方法
1)同优先级线程组成先进先出队列(先到先服务),使用时间片策略
2)对高优先级,使用优先调度的抢占式策略
线程的优先级:
1.最低优先级
public final static int MIN_PRIORITY = 1;
2.中等优先级,默认
public final static int NORM_PRIORITY = 5;
3.最高优先级
public final static int MAX_PRIORITY = 10;
设置|获取优先级:
1.getPriority() :返回线程优先值
2.setPriority(int newPriority) :改变线程的优先级
注意:
1.线程创建时继承父线程的优先级
2.低优先级只是获得调度的概率低,并非一定是在高优先级线程之后才被调用
实例:
package com.qwy7;
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i <= 5; i++) {
//打印当前线程名称和优先级
System.out.println(Thread.currentThread().getName() + "--" +Thread.currentThread().getPriority());
}
}
}
public class TestThreadPriority {
public static void main(String[] args) {
//创建线程对象
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
//设置线程名称
t1.setName("线程--A");
t2.setName("线程--B");
t3.setName("线程--C");
//设置线程优先级
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
运行可能的结果:
线程–A--10
线程–A--10
线程–A--10
线程–A--10
线程–C--1
线程–B--5
线程–A--10
线程–A--10
线程–B--5
线程–B--5
线程–B--5
线程–B--5
线程–B--5
线程–C--1
线程–C--1
线程–C--1
线程–C--1
线程–C--1
从打印结果看,并不是线程的优先级越高就一定会先执行,其实哪个线程先执行有CPU调度决定,只是优先级高的线程能获取更大的执行几率而已。
未完待续
=============================================================================================
如有不妥之处,欢迎大家给予批评指出,如果对您有帮助,给留下个小赞赞哦
==============================================================================================