黑马程序员技术交流社区
标题:
关于多线程的一个小疑问
[打印本页]
作者:
tonygone
时间:
2013-7-17 14:22
标题:
关于多线程的一个小疑问
本帖最后由 tonygone 于 2013-7-18 08:09 编辑
public class Runner2 implements Runnable {
public void run() {
try {
for (int i = 0; i < 30; i++) {
System.out.println(i);
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("线程被中断");
return;
}
}
}
public class TestInterupt {
public static void main(String[] args) {
Runner2 runner2 = new Runner2();
Thread t = new Thread(runner2);
t.start();
try {
Thread.sleep(10000);
t.interrupt();
} catch (InterruptedException ex) {
System.out.println("主线程被中断");
}
}
}
复制代码
我编译并执行TestInterup输出的结果是
0
1
2
3
4
5
6
7
8
9
可是我之后将Runner2类进行改写,代码如下:
public class Runner2 implements Runnable {
public void run() {
try {
for (int i = 0; i < 30; i++) {
Thread.sleep(1000);
System.out.println(i);
}
} catch (InterruptedException ex) {
System.out.println("线程被中断");
return;
}
}
}
复制代码
为什么我再次编译执行TestInterup类,其输出的结果却是:
0
1
2
3
4
5
6
7
8
为什么这次没有输出9呢?
作者:
Candy
时间:
2013-7-17 15:17
我很疑惑
作者:
tonygone
时间:
2013-7-17 15:55
liukunaitasa 发表于 2013-7-17 15:00
楼主怎么编译通过的。两个public类
我没有放在一个java文件里:#
作者:
一木榜公
时间:
2013-7-17 17:37
本帖最后由 一木榜公 于 2013-7-17 17:38 编辑
main线程中:Thread.sleep(10000); t线程中:Thread.sleep(1000);
main线程执行到sleep,睡的时间是 t线程的10倍,也就是t线程能执行10次循环,然后中断。所以修改前你输出的是10个数。
1 2 3 4 5 6 7 8 9 10 (睡的次数)
0 1 2 3 4 5 6 7 8 9 中断了
修改后是线程先睡,
1 2 3 4 5 6 7 8 9 10 睡的次数
0 1 2 3 4 5 6 7 8 中断了
作者:
滔哥
时间:
2013-7-17 17:43
如果同学已经解决问题 请修改问题为已解决。
作者:
赵海洋
时间:
2013-7-17 17:59
路过,瞅瞅~~~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2