看下代码:
- public class ThreadA extends Thread {
-
- public static void main(String[] args) {
- ThreadA a = new ThreadA();
- System.out.println(a.getPriority());//5
- a.setPriority(8);
- System.out.println(a.getPriority());//8
- }
- }
线程优先级特性:
- 继承性:比如 A 线程启动 B 线程,则B线程的优先级与 A 是一样的。
- 规则性:高优先级的线程总是大部分先执行完,但不代表高优先级线程全部先执行完。
- 随机性:优先级较高的线程不一定每一次都先执行完。
05、线程的停止
- stop() 方法,这个方法已经标记为过时了,强制停止线程,相当于 kill -9。
- interrupt() 方法,优雅的停止线程。告诉线程可以停止了,至于线程什么时候停止,取决于线程自身。
看下停止线程的代码:
- public class InterruptDemo {
- private static int i ;
- public static void main(String[] args) throws InterruptedException {
- Thread thread = new Thread(() -> {
- //默认情况下isInterrupted 返回 false、通过 thread.interrupt 变成了 true
- while (!Thread.currentThread().isInterrupted()) {
- i++;
- }
- System.out.println("Num:" + i);
- }, "interruptDemo");
- thread.start();
- TimeUnit.SECONDS.sleep(1);
- thread.interrupt(); //不加这句,thread线程不会停止
- }
- }
(编辑:西安站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|