Thread.sleep() 与 Thread.currentThread().sleep()区别
搜索了下百度,google,得到的答复都是没有区别
觉得很奇怪,不可能没区别吧?
在单个线程下应该一样,但是有多个线程还是没区别?在多个线程下,Thread.sleep()是不是当前线程sleep呢,如果是的话,那两者不是真的没区别了? 那currentThread()方法到底有什么用,难道就是为了得到个Thread对象?
Thread.sleep() 与 Thread.currentThread().sleep()区别到底是什么啊
[最优解释]
没有区别,你看下JDK的Thread.java实现就知道了。这个问题还在这里问....不该啊......送积分啊
[其他解释]
static void sleep(long millis)
在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响。
static Thread currentThread()
返回对当前正在执行的线程对象的引用。
很明显没啥区别
其实还有一个类似的方法,就是java.util.concurrent下面的:
void sleep(long timeout)
使用此单元执行 Thread.sleep.这是将时间参数转换为 Thread.sleep 方法所需格式的便捷方法。
[其他解释]
javadoc说得相当明白了, sleep的方法的doc
/**
* 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.
*
* @param millis the length of time to sleep in milliseconds.
* @exception InterruptedException if any thread has interrupted
* the current thread. The <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
* @see Object#notify()
*/
其实类似的还有好多, 例如Class.getResourceAsStream和ClassLoader.getResourceAsStream, 功能一样, 只是寻找的方法有点不一样而已
[其他解释]
区别当然是有了。第一种方式是只调用sleep静态方法;第二种是获取对象后再调用sleep静态方法。显然第二种方式效率要低一些,因为多了一次函数调用,而且通过对象调用静态方法也不太符合“静态”的定义(静态成员最好通过类名直接访问),但功能上是一致的。当需要调用非静态方法时使用第二种方式,否则直接使用第一种方式。
[其他解释]
在一个县城的情况下,没啥区别,但是在多线程时时有区别的。lz可以自己试试,特别是在多线程,每个线程处于不同状态下时,区别很明显。
[其他解释]
没区别,楼上说的很清楚了。
[其他解释]
算了 来打哥酱油吧
[其他解释]
呵呵,这个说的很明白。没有区别
就像王,倒过来写还是王一样
呵呵,祝楼主好运
[其他解释]
学习了~
[其他解释]
sleep方法是静态的,执行的结果是一样的。但是第二种写法画蛇添足,也不符合规范。
[其他解释]
打酱油,混分
[其他解释]
学习学习
[其他解释]
能举个例子吗?
[其他解释]
/**
* 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.
*
* @param millis the length of time to sleep in milliseconds.
* @exception InterruptedException if any thread has interrupted
* the current thread. The <i>interrupted status</i> of the
* current thread is cleared when this exception is thrown.
* @see Object#notify()
*/
public static native void sleep(long millis) throws InterruptedException;
/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
public static native Thread currentThread();
就是同一个对象,当你起一个main单线程的时候,就可以很容易发觉,你无论 currentThread();
还是Thread,线程根本不会变多。跟简单点说。
public static void main(String args[]) {
System.out.println(Thread.activeCount());
System.out.println(Thread.currentThread().getId());
System.out.println(Thread.activeCount());
}
输出都是1
[其他解释]
学习学习!~!~
