在我的主線程中,我創建並啓動了四個線程(A,B,C,D
),它們每隔500到1000ms在控制檯上打印字母和數字。 例如A1,A2,A3
等如何使隨機線程等待,然後在恆定時間後喚醒
主線程假設暫停隨機Letter
線程每隔100ms然後喚醒它。 2秒後,它假設全部殺死它們。
我的問題是,我不能暫停隨機Letter
線程將喚醒它,因爲我得到:IllegalMonitorStateException
我的主線程類:
public class Main extends Thread {
private boolean alive;
private ArrayList<Letter> letters;
private Letter toStop;
public static Object mutex;
public Main() {
letters = new ArrayList<Letter>();
alive = true;
mutex = new Object();
}
public void run() {
try {
Timer timer = new Timer();
timer.schedule(new StopTask(timer, this), 2 * 1000);
letters.add(new Letter());
letters.add(new Letter());
letters.add(new Letter());
letters.add(new Letter());
for (Letter letter : letters) {
new Thread(letter).start();
}
while (alive) {
synchronized (mutex) {
toStop = letters.get((int) (Math.random() * letters.size()));
System.out.println(toStop.getLetter() + " spi");
mutex.wait();
Thread.sleep(100);
mutex.notify();
}
for (Letter letter : letters) {
letter.kill();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void kill() {
alive = false;
}
}
和我Letter
類:
class Letter implements Runnable {
private static int ID;
private char letter;
private int counter;
private boolean alive;
public Letter() {
letter = (char) ('A' + ID);
alive = true;
ID++;
}
@Override
public void run() {
try {
while (alive) {
System.out.println(letter + "" + counter);
counter++;
Thread.sleep((int) (Math.random() * 501 + 500));
}
System.out.println("Watek " + letter + " sie zakonczyl");
} catch (Exception e) {
}
}
public void kill() {
alive = false;
}
public char getLetter() {
return letter;
}
}
StopTask
:
import java.util.Timer;
import java.util.TimerTask;
public class StopTask extends TimerTask {
private Timer timer;
private Main main;
public StopTask(Timer timer, Main main) {
this.timer = timer;
this.main = main;
}
public void run() {
System.out.println("Time's up!");
main.kill();
timer.cancel(); //Not necessary because we call System.exit
}
}
您正在同步'mutex'並在'toStop'上調用'wait()'。你應該調用'mutex.wait()'而不是 –
@NitinDandriyal,但我想暫停'toStop'直到我調用notify。 – Yoda
@NitinDandriyal我更新'Main'中的'run'線程永遠不會結束。我現在添加了'StopTask',複製的代碼將被編譯並運行。 – Yoda