import java.util.Date;public class SleepThreadTest {
public static void main(String[] args) {
run1 r = new run1();
Thread t = new Thread(r); while (true) {
t.start();
try {
t.sleep(1000);
} catch (InterruptedException e) {
return;
}
} try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
t.interrupt();
}
}class run1 implements Runnable { public void run() {
System.out.println(new Date());
}}
为什么主线程后面
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
t.interrupt();
会报错...
public static void main(String[] args) {
run1 r = new run1();
Thread t = new Thread(r); while (true) {
t.start();
try {
t.sleep(1000);
} catch (InterruptedException e) {
return;
}
} try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
t.interrupt();
}
}class run1 implements Runnable { public void run() {
System.out.println(new Date());
}}
为什么主线程后面
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
t.interrupt();
会报错...
因为 while (true) 是死循环 后面 代码 执行不到的。
t.start();
try {
t.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
你执行了这个,要么一直不抛异常,无限循环执行,要么抛出异常,直接返回,下面的语句根本没有执行的机会
while (key) {
t.start();
key=false;
try {
t.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
一个线程启动start() 线程启动了 进入运行状态 打印了一句话后线程完了 进入死亡状态
如果在调用start() 方法在启动这个进程 就会抛出 IllegalThreadException
t.start();
sleep(10000);//睡个10s
t.interrupt();void run()
{
while(true){
System.out.ptintln(new Date());
sleep(100)//睡个0.1s
}
}
让当前执行到此的线程sleep一定时间 看看JDK就知道
public static void main(String[] args) {
run1 r = new run1();
Thread t = new Thread(r);
t.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.interrupt();
}
}class run1 implements Runnable { public void run() {
while (true) {
System.out.println(new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
} }
}}
System.out.println(new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
} }
这不是死循环吗?
当catch到Interrupted就会return...