代码如下:public class SleepTest { public static void main(String[] args) throws InterruptedException {
SleepThread st = new SleepThread();
st.start();
while (true) {
st.sleep(3000);
                        System.out.println("main thread.");
}
}
static class SleepThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("not sleep.");
}
}
}
}打印结果都是"not sleep.",没有看"main thread."
在主线程中调用st线程的sleep方法,为什么st没有休眠?好像st.sleep方法阻塞了主线程。如果将代码改为如下:public class SleepTest { public static void main(String[] args) throws InterruptedException {
SleepThread st = new SleepThread();
st.sleep(3000);
st.start();
System.out.println("main thread.");
}
static class SleepThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("not sleep.");
}
}
}
}因为st线程休眠了,本来以为会先执行主线程打印"mian thread.",但是结果是休眠了3秒后,才打印"main thread.",好像st.sleep方法阻塞了主线程。

解决方案 »

  1.   

    sleep睡得是当前线程,sleep是静态方法,即使你用对象去调用,实际上执行的是Thread.sleep()。所以st根本没睡。睡得是执行main方法的主线程自身。程序运行3秒后才会出现main thread,你仔细找。
      

  2.   

    1、最主要是要理解sleep的是静态方法,应该使用类名.sleep()这种方式调用,只有当前运行的线程才可能sleep,如果不是当前线程,就根本扯不上sleep了,这应该就是为啥sleep被设计为静态方法的原因
    2、第一段代码也会输出main-thread,可能是因为输出的次数太少你看不到,在linux上可以这样验证:
       java SleepTest > out.txt
       过一段时间停止程序,然后用grep main out.txt会发现有几个main thread
    3、第二个程序有可能先输出main thread.也有可能先输出not sleep,主要是看怎么调度