在Thread类中注释标明有两种方式创建新的执行线程:
- 一种是声明一个类是Thread的子类。这个子类应该重写类Thread的run方法。然后可以分配和启动子类的实例
- 创建线程的另一种方法是声明一个实现Runnable接口的类。这个类然后实现run方法。然后可以分配类的实例,在创建Thread时作为参数传递,并启动
两种方式对比:
- 从java语法方面来看,java没有多继承,如果使用继承Thread的方式,就不能再继承其他类,限制了代码的可扩展性
- 从效率方面来看,如果通过实现Runnable接口的方式,可以作为一个任务当做参数传入到线程中,这时的线程可以使用线程池。而通过继承的方式,每次创建和销毁线程相对来讲会消耗资源,效率并不高
stop():已弃用,停止方式会使业务逻辑不完整
正确方式 interrupt() | 将中断位标记设置位true |
isInterrupted() | 返回该线程的中断标记位 |
interrupted() | 返回重置当前线程的中断标记位 |
interrupt():推荐使用,简单来讲就是向线程发送一个中止信号,但该线程是否中止,什么时候中止,取决于目标线程的应答
isInterrupted():返回该线程的中断标记位,可以搭配interrupt()组合使用
使用interrupt()中止一个正在运行的线程:
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
// 搭配isInterrupted()正常中止线程
if (Thread.currentThread().isInterrupted()) {
System.out.println("thread 正常中止");
break;
}
}
});
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
中断正在休眠的线程:
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
synchronized (lock) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("flag");
}
});
thread.start();
// 此时中断TIME_WATING状态的线程,会抛出InterruptedException
// wait(), wait(long),wait(long, int) join(), join(long), join(long, int), sleep(long), sleep(long, int), cleared and it will receive an InterruptedException.
// interrupt方法注释明确标注:如果在使用上述方法期间被打断,会重置标记位并抛出一个异常
thread.interrupt();
}
**********运行结果****************
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.nuc.demo.thread.CarThread.lambda$main$0(CarThread.java:33)
at java.lang.Thread.run(Thread.java:748)
false
备注:凡是会抛出InterruptedException信息的方法,一般都会在其抛出异常之前将当前线程的中断标志位重置为false
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)