sleep()方法是Thread的一个方法,表示可以让一个线程进入睡眠,指定的时间,但是当达到指定时间之后并不会马上运行,
而是转到可运行状态,这是因为线程的调度机制再恢复线程的运行时也是需要时间的,
当一个对象调用了sleep()之后,并不会释放他所持有的对象的锁,所以不影响其他线程访问.
使用sleep()方法时必须要捕获异常 或抛出一个 InteruptedException异常.
实现线程的方式有两种:
- 继承java.lang.Thread,并重写它的run()方法,将线程的执行主体放入其中。
- 实现java.lang.Runnable接口,实现它的run()方法,并将线程的执行主体放入其中
1 run()方法:
package com;
public class MyThread extends Thread{
public void run(){
try{
System.out.println("run threadName="+this.currentThread().getName()+"begin");
Thread.sleep(5000);
System.out.println("run threadName="+this.currentThread().getName()+"end");
}catch(InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyThread thread = new MyThread();
System.out.println("begin="+System.currentTimeMillis());
thread.run();
System.out.println("end="+System.currentTimeMillis());
}
}
输出 begin=1458183530490
run threadName=mainbegin
//睡眠5000毫秒
run threadName=mainend
end=1458183535491
start()方法:
package com;
public class MyThread extends Thread{
public void run(){
try{
System.out.println("run threadName="+this.currentThread().getName()+"begin");
Thread.sleep(5000);
System.out.println("run threadName="+this.currentThread().getName()+"end");
}catch(InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyThread thread = new MyThread();
System.out.println("begin="+System.currentTimeMillis());
thread.start();
System.out.println("end="+System.currentTimeMillis());
}
}
输出 begin=1458183694347
end=1458183694348
run threadName=Thread-0begin
//睡眠5000毫秒
run threadName=Thread-0end
本文详细介绍了Java中Thread.sleep()方法的使用,解释了它如何让线程进入睡眠状态并恢复运行的过程。在使用sleep()方法时,线程不会释放对象锁,且必须捕获InterruptedException。通过示例展示了直接调用run()和使用start()启动线程的区别,以及它们在输出上的差异。
869

被折叠的 条评论
为什么被折叠?



