代码如下: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方法阻塞了主线程。
解决方案 »
- applet读取本地客户端文件
- 简单问题
- 我是一个大二女生 初次学JAVA 本来C就学的不太好 我想知道 用JAVA编九九乘法表怎么编
- java SWT
- 请教高分高手
- SWT中setToolTipText怎么弹出网页内容
- 中文输入法引起java虚拟机崩溃,有什么好的解决办法?
- org.apache.axis.tools.ant.wsdl.Java2WsdlAntTask 问题!!!!!!,请看看!
- 如何打包和调用自己的类包?****************************************************************
- Socket获取InputStream的问题
- 求设置窗体中菜单栏的大小问题
- 核心技术出错了
2、第一段代码也会输出main-thread,可能是因为输出的次数太少你看不到,在linux上可以这样验证:
java SleepTest > out.txt
过一段时间停止程序,然后用grep main out.txt会发现有几个main thread
3、第二个程序有可能先输出main thread.也有可能先输出not sleep,主要是看怎么调度