【发布时间】:2015-04-25 11:51:17
【问题描述】:
我能够理解线程和中断。我试图映射从 Oracle 教程中学到的基本概念,以更好地理解中断的概念。我开发了这个例子并努力理解输出是如何在这里发挥作用的。我只是不明白。所以我的想法是请人帮助我理解这个程序的输出,这将使我更清楚地了解中断的底层功能。
public class ThreadSleepTest {
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
Thread one = new Thread(myRunnable);
one.setName("Fred");
Thread two = new Thread(myRunnable);
two.setName("Lucy");
Thread three = new Thread(myRunnable);
three.setName("Ricky");
one.start();
two.start();
three.start();
//Thread.sleep(1000);
one.interrupt();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int x = 1; x < 4; x++) {
System.out.println("Run by: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.out.println("Exception occured");
}
}
System.out.println("Do something");
}
}
这是我的控制台的输出。
Run by: Lucy
Run by: Fred
Run by: Ricky
Exception occured
Run by: Fred
Run by: Fred
Run by: Lucy
Run by: Ricky
Do something
Run by: Lucy
Run by: Ricky
Do something
Do something
【问题讨论】:
-
我已阅读并理解,但输出仍然令人困惑。
-
令人困惑的原因是什么?你期待什么?为什么?
-
@EJP 的建议值得一票!
-
@benz 并发非常棘手。我相信 EJP 的建议是,如果程序的输出让你感到困惑,那么找出什么样的输出会更容易混淆。
标签: java multithreading interrupt interrupted-exception