多线程中的sleep()

来源:互联网 发布:数据迁移 编辑:程序博客网 时间:2024/06/01 11:53

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

0 0
原创粉丝点击