方法如下:
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呢?多线程
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呢?多线程
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货