java——中断线程

2019年2月18日22:58:01 发表评论 1,530 views

发现个好东西: 一个免费短链生成项目:“ https://www.isok.co”一个可以生成所有短链的服务,isok.co的这个含义能覆盖所有短链含义isok, 我试过了很不错,都可以试试

/**
 * 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: