目录
哪些情况可以终止线程的进行?
题目解析
答案选C
A:线程使用sleep()方法,使线程挂起一段时间,并不是终止
B: 创建一个新线程时,对之前的线程没有影响
C:抛出一个例外,线程终止
D: 并不是终止,而是抢占,进程是资源分配的最基本单位,同一个进程创建的不同线程共享这些资源,当某一个线程优先级比较高时,它就会抢占其他线程的资源,导致其他线程没有资源可用,会造成阻塞
线程结束的三个原因
线程结束的三种方法-具体分析
1,使用标志位推出线程
一般 run()方法执行完,线程就会正常结束,然而,常常有些线程是伺服线程。它们需要长时间的运行,就要使用一个变量控制循环
public class ThreadSafe extends Thread {
public volatile boolean exit = false;
public void run() {
while (!exit){
//do something
}
}
}
2,使用stop方法强制终止线程
程序中可以直接使用 thread.stop()来强行终止线程,但是 stop 方法是很危险的,就象突然关 闭计算机电源,而不是按正常程序关机一样,可能会产生不可预料的结果,不安全主要是: thread.stop()调用之后,创建子线程的线程就会抛出ThreadDeatherror 的错误,并且会释放子 线程所持有的所有锁。
3,使用interrupt终止线程
当线程处于两种状态时,使用interrpt终止
public class MyThread extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 500000; i++) {
if (interrupted()) {
System.out.println("已经是停止状态了");
throw new InterruptedException();//中断异常
}
System.out.println("i=" + (i + 1));
}
System.out.println("我在for下面");
} catch (InterruptedException e) {
System.out.println("进run方法中的catch了!");
e.printStackTrace();
}
}
}
public class ThreadInterrupt extends Thread {
public void run() {
try {
sleep(50000); // 延迟50秒
}
catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception {
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("在50秒之内按任意键中断线程!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("线程已经退出!");
}