/** * 安全中断Thread类型的线程 */ public class EndThread { private static class UseThread extends Thread{ public UseThread(String name) { super(name); } @Override public void run() { String threadName = Thread.currentThread().getName(); while(!Thread.interrupted()) { System.out.println(threadName+" is running!"); } System.out.println(threadName+" interrupt flag is "+isInterrupted()); } } public static void main(String[] args) throws InterruptedException { Thread endThread = new UseThread("endThread"); endThread.start(); Thread.sleep(20); endThread.interrupt(); } }
/** * 安全中断Runnable类型的线程 */ public class EndRunnable { private static class UseRunnable implements Runnable{ public void run() { String threadName = Thread.currentThread().getName(); while(!Thread.currentThread().isInterrupted()){ System.out.println(threadName+" is running!"); } System.out.println(threadName+" interrupt flag is "+Thread.currentThread().isInterrupted()); } } public static void main(String[] args) throws InterruptedException { Runnable useRunnable = new UseRunnable(); Thread endThread = new Thread(useRunnable,"endThread"); endThread.start(); Thread.sleep(20); endThread.interrupt(); } }