java——中断线程

2019年2月18日22:58:01 发表评论 1,258 views
/**
 * Created by xabcd on 2019/2/18.
 */
public class stopThread implements Runnable
{
    public void run()
    {
        try {
            System.out.println("在run()方法中,-这个线程休眠20秒");
            Thread.sleep(20000);
            System.out.println("在run()方法中,-这个线程休眠20秒");
        }
        catch (InterruptedException i)
        {
            System.out.println("在run方法中-中断线程");
            return;
        }
//添加finally后将能够打印出下面两行
        System.out.println("在run()方法中-休眠之后继续完成");
        System.out.println("在run()方法中-正常退出");

    }
    public static void main(String args[])
    {
        stopThread tt = new stopThread();
        Thread t = new Thread(tt);
        t.start();
        try {
            Thread.sleep(20);
        }
        catch (InterruptedException x){}
        System.out.println("在main方法中=中断其它线程");
        t.interrupt();
//        try {
//            Thread.sleep(1); //尝试将此块注释或显示,将看到打印的顺序区别
//        }
//        catch (InterruptedException x){}
        System.out.println("在main方法中-退出");


    }
}





结果:
在run()方法中,-这个线程休眠20秒
在main方法中=中断其它线程
在main方法中-退出
在run方法中-中断线程




发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: