代码如下: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方法阻塞了主线程。
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方法阻塞了主线程。
2、第一段代码也会输出main-thread,可能是因为输出的次数太少你看不到,在linux上可以这样验证:
java SleepTest > out.txt
过一段时间停止程序,然后用grep main out.txt会发现有几个main thread
3、第二个程序有可能先输出main thread.也有可能先输出not sleep,主要是看怎么调度