1 线程中断不是线程终止,被中断的线程可以继续运行。
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Interrupted {
public static void main(String[] args) {
Thread sleep = new Thread(new SleepRunner(),"SleepRunner");
Thread busy = new Thread(new BusyRunner(), "BusyRunner");
//sleep.start();
busy.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("i am TimeUnit interrupted , i output message");
e.printStackTrace();
}
sleep.interrupt();
busy.interrupt();
System.out.println("SleepRunner interrupt is "+ sleep.isInterrupted());
System.out.println("BusyRunner interrupt is "+ busy.isInterrupted());
}
}
class SleepRunner implements Runnable{
@Override
public void run() {
while(true){
if(Thread.currentThread().isInterrupted()){
System.out.println("i am SleepRunner , i am interrupted");
}
try {
Thread.sleep(10000);
System.out.println("sleep and running");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("i am interrupted , i output message");
e.printStackTrace();
}
}
}
}
class BusyRunner implements Runnable{
@Override
public void run() {
while(true){
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
if(Thread.currentThread().isInterrupted()){
System.out.println("i am busy , i am interrupted");
}
System.out.println("running");
}
}
}