怎么停止线程?
Java多线程有三种停止线程的方法:
- 使用stop()方法强制线程退出,但是此方法会残留不完整数据,因为stop会解除线程获取的所有锁。现在已经不使用这种方法了。
- 设置标志位,使线程正常退出,setFlag() 方法;
标志位:myThread.setFlag(false);这样调用,该线程就被终止了 - 使用Thread类的interrupt()方法中断线程,但是原理也是设置标志位;
interrupt只会改变中断状态,并不会中断一个线程,如果当前线程处于非阻塞状态,interrupt会将中断标志设置为true,在线程工作的过程中一旦线程进入了阻塞状态,比如调用了wait,join,sleep方法,中断标志就会被设置为false,并且抛出InterruptException异常,Thread类提供的public boolean isInterrupted()可以检测当前线程状态是否为中断状态,interrupt可以响应阻塞,在抛出的异常中,可以在try,catch块中停止线程,设置标志位。
class MyThread implements Runnable {
private boolean flag = true;
@Override
public void run() {
int i = 1;
while (flag) {
try {
/**
* 这⾥阻塞之后,线程被调⽤了interrupte()⽅法,
* 清除中断标志,就会抛出⼀个异常
* java.lang.InterruptedException
*/
Thread.sleep(1000);
boolean bool = Thread.currentThread().isInterrupted();
if (bool) {
System.out.println("⾮阻塞情况下执⾏该操作。。。线程状态" +
bool);
break;
}
System.out.println("第"+i+"次执⾏,线程名称
为:"+Thread.currentThread().getName());
i++;
} catch (InterruptedException e) {
System.out.println("退出了");
/**
* 这⾥退出阻塞状态,且中断标志被系统会⾃动清除,
* 并且重新设置为false,所以此处bool为false
*/
boolean bool = Thread.currentThread().isInterrupted();
System.out.println(bool);
//退出run⽅法,中断进程
return;
}
}
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"⼦线程A");
thread1.start();
Thread.sleep(3000);
thread1.interrupt();
System.out.println("代码结束");
}
}
结果:
线程优先级?
线程的优先级指的是,线程的优先级越⾼越有可能先执⾏,但仅仅是有可能⽽已。
- 设置优先级方法:void setPriority(int newPriority);
- 取得线程优先级:int getPriority();
- 线程是有继承关系的,⽐如当A线程中启动B线程,那么B和A的优先级将是⼀样的。
- 对于优先级设置的内容可以通过Thread类的⼏个常量来决定
- 最⾼优先级:public final static int MAX_PRIORITY = 10;
- 中等优先级:public final static int NORM_PRIORITY = 5;
- 最低优先级:public final static int MIN_PRIORITY = 1;
线程守护?
java 中有两种线程:⽤户线程和守护线程:默认创建的线程就是用户线程,包括主线程main,守护线程是陪伴线程,只要jvm中还有线程没有终止,守护线程就一直工作,通过setDaemon(true)将线程对象设置为守护线程,垃圾回收线程就是典型的守护线程。