多线程中的sleep()

本文详细介绍了Java中Thread.sleep()方法的使用,解释了它如何让线程进入睡眠状态并恢复运行的过程。在使用sleep()方法时,线程不会释放对象锁,且必须捕获InterruptedException。通过示例展示了直接调用run()和使用start()启动线程的区别,以及它们在输出上的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sleep()方法是Thread的一个方法,表示可以让一个线程进入睡眠,指定的时间,但是当达到指定时间之后并不会马上运行,

而是转到可运行状态,这是因为线程的调度机制再恢复线程的运行时也是需要时间的,

当一个对象调用了sleep()之后,并不会释放他所持有的对象的锁,所以不影响其他线程访问.

使用sleep()方法时必须要捕获异常 或抛出一个 InteruptedException异常.

实现线程的方式有两种: 

  1. 继承java.lang.Thread,并重写它的run()方法,将线程的执行主体放入其中。
  2. 实现java.lang.Runnable接口,实现它的run()方法,并将线程的执行主体放入其中
   直接调用run()方法和start()方法

   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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值