一:先sleep()然后再用interrupt()停止
public class MyThread extends Thread {
@Override
public void run() {
super.run();
try{
System.out.println("MyThread-run-begin");
//当线程MyThread状态标识为true时,调用sleep()
//这个时候会抛出异常,
// 并且将线程MyThread状态标识为false
//最后停止该线程
Thread.sleep(200000);
System.out.println("MyThread-run-end");
}catch (InterruptedException e){
//异常后,线程MyThread的状态标识为false了
System.out.println("MyThread-run-catch..."+this.isInterrupted());
e.printStackTrace();
}
}
}
public class RunThread {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
//启动线程MyThread
myThread.start();
//让线程main睡一会儿,以保障MyThread能运行
Thread.sleep(2000);
//将MyThread状态标识为true
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main-catch");
e.printStackTrace();
}
System.out.println("main-end");
}
}
运行结果
二:先interrupt(),然后sleep()
public class MyThread extends Thread{
@Override
public void run() {
super.run();
try{
System.out.println("MyThread-run-begin");
//当前线程MyThread进入睡眠状态时,
//由于线程MyThread状态标识为true,
//此时会抛出异常,并将线程标识清除为false
//线程停止
Thread.sleep(20000);
System.out.println("MyThread-run-end");
}catch (InterruptedException e){
System.out.println("MyThread-catch..."+Thread.currentThread().isInterrupted());
e.printStackTrace();
}
}
}
public class RunThread {
public static void main(String[] args) {
System.out.println("main-begin");
MyThread myThread = new MyThread();
//启动MyThread,并将线程MyThread状态标识为true
myThread.start();
myThread.interrupt();
System.out.println("main-end");
}
}
网友评论