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