实现接口Runnable的线程如何中断

实现接口Runnable的线程如何中断

package ch1.base.safeend;

public class EndRunnable {
    private static class UserRunnable implements Runnable{
        public void run(){
            while(!Thread.currentThread().isInterrupted()){
                System.out.println(Thread.currentThread().getName()+" I am impelments Runnable.");
            }
            System.out.println(Thread.currentThread().getName()+" interrupt flag is "+Thread.currentThread().isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException{
        UserRunnable userRunnable = new UserRunnable();
        Thread endTrhead = new Thread(userRunnable,"endThread");
        endTrhead.start();
        Thread.sleep(1);
        endTrhead.interrupt();
    }

    /**
     * 结果类似
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread I am impelments Runnable.
     endThread interrupt flag is true

     Process finished with exit code 0

     */
}

你可能感兴趣的:(实现接口Runnable的线程如何中断)