关于java中 interrupt,中断线程,我怎么怎样都不能中断
发布网友
发布时间:2022-05-15 07:41
我来回答
共3个回答
热心网友
时间:2023-10-14 02:10
java线程中interrupt执行之后,并不能阻止线程执行,可以使用变量来控制,如下代码:
package com.qiu.lin.he;
import java.io.IOException;
public class CeShi extends Thread {
volatile boolean stop = false;
public static void main(String[] args) throws IOException,
InterruptedException {
CeShi thread = new CeShi();
System.out.println("Starting thread...");
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Asking thread to stop...");
thread.stop = true;
Thread.sleep(3000);
System.out.println("Stopping application...");
}
@Override
public void run() {
while (!stop) {//当stop变量为false时,则停止
System.out.println("Thread is running...");
long time = System.currentTimeMillis();
while (System.currentTimeMillis() - time < 1000 && !stop) {
}
}
System.out.println("Thread exiting under request...");
}
}
运行结果如下:
热心网友
时间:2023-10-14 02:11
以下为我的实现代码,可以试下:
import java.util.Date;
public class TestInterrupt {
/**
* @param args
*/
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
int i = 0;
while(i++<=10){ //当i=10时,终止标志设为true
thread.stopThread();
}
}
}
class MyThread extends Thread {
private boolean stopFlag = false ; //设置终止标志为false
public void run() {
while(true) {
System.out.println("===" + new Date() + "===");
try {
sleep(1000);
if(stopFlag){//当终止标志为true时,跳出循环体,线程结束
interrupt(); //当触发interrupt操作时,会
}
} catch(InterruptedException e) {
break;
}
}
}
public void stopThread(){
stopFlag = true;
}
}
热心网友
时间:2023-10-14 02:11
catch (InterruptedException e) {
thread.interrupt();
}
应该写成:
catch (InterruptedException e) {
}
thread.interrupt();