使主线程等待其他线程完成



我有以下Switch类基本上togglesisOn

我主要想做的是thread1thread2,启动它们, 然后睡 5 秒钟,然后interrupt他们,我想我这样做是正确的

除了主线程应该等待两个线程完成,这就是我添加的地方

thread1.join()
thread2.join()

但这会导致线程永远运行并且没有抛出异常,我该怎么办? 还是主要已经在等待他们完成?

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();
}
}

您需要将以下行放在catch块中:

Thread.currentThread().interrupt();

此外,您不需要以下行:

if (Thread.currentThread().isInterrupted()) {
break;
}

演示:

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) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();// Add this line
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();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.interrupt();
thread2.interrupt();
}
}

最新更新