【发布时间】:2021-12-27 12:03:04
【问题描述】:
我是 Java 编程新手,第一次尝试线程。我创建了一个线程来打印偶数,然后创建一个线程来打印奇数。在奇数线程中,在要打印的数字 11 之后有一个 suspend() 方法。之后还有另一个块打印从 13 到 21 的奇数。在 main() 中,我加入了 2 个线程。在主函数中,我首先调用线程 t1(偶数),然后将其与线程 t2(奇数)连接。由于有暂停,它会在打印 11 后暂停输出,它会在那里暂停。但在那之后,当我调用 t2.resume() 时,它不会继续打印 13 到 21。为什么它不打印其余部分?我怎样才能让它恢复?
这是代码,请看:
class Hi extends Thread {
public void run(){
try{
for(int i=0; i<=10; i++){
System.out.println("1st: " + (2*i));
sleep(100);
}
} catch(Exception e){
System.out.println(e);
}
}
}
class Hello extends Thread {
public void run(){
try {
for(int i=0; i<=5; i++){
System.out.println("2nd: " +(2*i+1));
}
suspend();
System.out.println(" Resumes again");
for(int i=6; i<=10; i++){
System.out.println("2nd: " +(2*i+1));
}
} catch(Exception e){
System.out.println(e);
}
}
}
public class thread {
public static void main(String args[]){
Hi t1 = new Hi();
Hello t2 = new Hello();
t1.start();
try {
t1.join();
} catch (Exception e) {
}
t2.start();
t2.resume();
}
}
输出:
1st: 0
1st: 2
1st: 4
1st: 6
1st: 8
1st: 10
1st: 12
1st: 14
1st: 16
1st: 18
1st: 20
Exception in thread "main" 2nd: 1
java.lang.IllegalThreadStateException
2nd: 3
2nd: 5
2nd: 7
2nd: 9
2nd: 11
at java.base/java.lang.Thread.start(Thread.java:791)
at thread.main(thread.java:57)
在此之后程序没有退出,我必须在终端中手动(ctrl+c)退出程序。
【问题讨论】:
-
为什么要发布格式不正确的代码?理解别人的代码已经够难的了,为什么要让它变得更难呢?
-
另外,
suspend()已被弃用——因此您不应调用此方法(或扩展 Thread,就此而言)。 -
一开始的那堵文字墙也是如此。您希望其他人花时间帮助您,所以请尽可能简单:编写易于消化的内容。
-
然后:空的 catch 块是一个非常糟糕的做法。永远不要那样做,至少打印异常。否则,您只是在抑制错误。
标签: java multithreading exception