【发布时间】:2020-09-21 02:17:23
【问题描述】:
我有以下Switch 类,基本上是toggles isOn
我想主要是制作thread1 和thread2,启动它们,
然后睡 5 秒,然后interrupt 他们,我认为我这样做是正确的
除了主线程应该等待两个线程完成,这就是我添加的地方
thread1.join()
thread2.join()
但这导致线程永远运行并且没有抛出异常,我应该怎么做?还是 main 已经在等待他们完成?
public class Switch implements Runnable {
private static boolean isOn;
private String name;
private static final Object lockedObject = new Object();
public Switch(String name) {
this.name = name;
}
public void toggle() {
System.out.println(name + ": " + isOn);
synchronized (lockedObject) {
isOn = !isOn;
}
}
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
synchronized (lockedObject) {
toggle();
}
}
}
public static void main(String[] args) throws InterruptedException {
Switch switch1 = new Switch("switch1");
Switch switch2 = new Switch("switch2");
Thread thread1 = new Thread(switch1);
Thread thread2 = new Thread(switch2);
thread1.start();
thread2.start();
// thread1.join();
// thread2.join();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.interrupt();
thread2.interrupt();
}
}
【问题讨论】:
-
“主线程应该等待两个线程完成” - 但它正在正确等待它们完成。你给它两个无限线程
while(true)循环,并告诉它等待无限线程完成。所以难怪这永远不会发生,因为线程运行无限循环。
标签: java multithreading