Thread类中sleep是为什么是静态方法

来源:互联网 发布:日志服务器软件 编辑:程序博客网 时间:2024/06/05 01:04

Thread sleep的含义

Thread类中sleep是静态方法,表示当前线程休眠。

Thread的API

    public static native void sleep(long millis) throws InterruptedException;

/**    
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds, subject to
     * the precision and accuracy of system timers and schedulers. The thread
     * does not lose ownership of any monitors.
     *

Thread.sleep是 使 当前 执行得线程  休眠,就是 Thread.sleep所在代码片段的线程


Thread sleep和实例.Slepp的区别???

package com.linkage.deadlock;
public class Thread_Sleep extends Thread{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true){
     System.out.println("执行线程");
        }
    }

     public static void main(String[] args) {
    Thread_Sleep tt=new Thread_Sleep();
    
    tt.start();
      
      while(true){
          System.out.println("main---------------------------");
    try {
        tt.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  
 
    }
     }
    
}



这个说明:tt.sleep还是在休眠主线程,而不是休眠 实例所在线程  

tt.sleep和 Thread.sleep效果 是一样的,  实际上都是 调用类的静态方法


为什么不设计成非静态的,当实例调用时,该实例休眠  ?

1、sleep是静态方法,那么在实现Runnable的线程类也能调用。
2、sleep是静态方法,所以sleep时候只是让出了cup却不能释对象锁,因为获取不到对象。???

3、线程和实例并不是对等的,不是一个线程是一个实例,是你创建的实例继承了Thread或者Runable,实现了run(),并调用start()的时候能执行多个线程,实例还是一个,线程却是多个。所以实例休眠线程就休眠了这个假设不成立。

如果sleep不是静态的, 只对当前进程作用. 而是实例方法, 那么应该和suspend有同样的问题, 死锁.

 



0 0
原创粉丝点击