看下代码:
- 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线程不会停止
- }
- }
看上面这段代码,主线程 main 方法调用 thread线程的 interrupt() 方法,就是告诉 thread 线程,你可以停止了(其实是将 thread 线程的一个属性设置为了 true ),然后 thread 线程通过 isInterrupted() 方法获取这个属性来判断是否设置为了 true。这里我再举一个例子来说明一下,
看代码:
- public class ThreadDemo {
- private volatile static Boolean interrupt = false ;
- private static int i ;
-
- public static void main(String[] args) throws InterruptedException {
- Thread thread = new Thread(() -> {
- while (!interrupt) {
- i++;
- }
- System.out.println("Num:" + i);
- }, "ThreadDemo");
- thread.start();
- TimeUnit.SECONDS.sleep(1);
- interrupt = true;
- }
- }
是不是很相似,再简单总结一下:
当其他线程通过调用当前线程的 interrupt 方法,表示向当前线程打个招呼,告诉他可以中断线程的执行了,并不会立即中断线程,至于什么时候中断,取决于当前线程自己。
线程通过检查自身是否被中断来进行相应,可以通过 isInterrupted() 来判断是否被中断。
这种通过标识符来实现中断操作的方式能够使线程在终止时有机会去清理资源,而不是武断地将线程停止,因此这种终止线程的做法显得更加安全和优雅。
06、线程的复位
两种复位方式:
- Thread.interrupted()
- 通过抛出 InterruptedException 的方式
然后了解一下什么是复位: (编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|