首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >1.5 sleep()方法

1.5 sleep()方法

作者头像
用户1134788
发布2018-01-05 11:49:16
2.2K0
发布2018-01-05 11:49:16
举报

方法sleep()的作用是在指定的毫秒数内让当前"正在执行的线程"休眠(暂停执行)。这个“正在执行的线程”是指this.currentThread()返回的线程。

注:this.currentThread()在IDE中报错,提示使用类名调用静态方法,但实际并不影响运行。

线程代码:

public class Thread1 extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("run threadName = " + this.currentThread().getName() + " begin");
            Thread.sleep(2000);
            System.out.println("run threadName = " + this.currentThread().getName() + " end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

执行代码:

public class Main {
    public static void main(String[] args) {
        Thread1 t1 = new Thread1();
        System.out.println("begin = " + System.currentTimeMillis());
        t1.run();
        System.out.println("end = " + System.currentTimeMillis());
    }
}

执行结果:

创建线程代码2:

public class Thread2 extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("run threadName = " + this.currentThread().getName() + " begin =" +System.currentTimeMillis());
            Thread.sleep(2000);
            System.out.println("run threadName = " + this.currentThread().getName() + " end =" +System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

创建执行代码:

public class Main {
    public static void main(String[] args) {
        Thread2 t2 = new Thread2();
        System.out.println("begin = " + System.currentTimeMillis());
        t2.start();
        System.out.println("end = " + System.currentTimeMillis());
    }
}

执行结果:

注:main与Thread2线程是异步执行的,所以先打印出begin与end,然后再打印run begin与run end

源码地址:https://github.com/lilinzhiyu/threadLearning

本文内容是书中内容兼具自己的个人看法所成。可能在个人看法上会有诸多问题(毕竟知识量有限,导致认知也有限),如果读者觉得有问题请大胆提出,我们可以相互交流、相互学习,欢迎你们的到来,心成意足,等待您的评价。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档