[英]How to make random thread wait then wake it up after constant time
在主线程中,我创建并启动四个线程( A,B,C,D
),每500到1000ms在控制台上打印一次字母和数字。 例如A1,A2,A3
等。
主线程假设每100毫秒暂停一次随机Letter
线程,然后将其唤醒。 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
}
}
您的代码示例不起作用,因为在不拥有对象监视器的情况下进行了wait()调用。
这是javadoc的解释: https : //docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
这是来自Javadoc的代码段:
公共最终void wait()引发InterruptedException
使当前线程等待,直到另一个线程为此对象调用notify()方法或notifyAll()方法。 换句话说,此方法的行为就像完全执行调用wait(0)一样。 当前线程必须拥有该对象的监视器。 线程释放此监视器的所有权,并等待直到另一个线程通过调用notify方法或notifyAll方法通知等待在此对象监视器上等待的线程唤醒。 然后,线程等待,直到它可以重新获得监视器的所有权并恢复执行。
与一个参数版本中一样,可能会产生中断和虚假唤醒,并且应始终在循环中使用此方法:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
此方法只能由作为该对象的监视器的所有者的线程调用。 有关线程可以成为监视器所有者的方式的描述,请参见notify方法。 抛出:IllegalMonitorStateException-如果当前线程不是对象监视器的所有者。 InterruptedException-如果任何线程在当前线程等待通知之前或之时中断了当前线程。 引发此异常时,将清除当前线程的中断状态。
我将重新设计代码以使线程自己等待,而不是被告知从外部等待。 例如,使用一些共享对象在线程之间共享状态。 我还将使用预定的线程执行器。 使生活更轻松: http : //docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
这是一个典型的生产者-消费者问题,并且有更好的解决方法。 由于我们正在解决眼前的问题,因此您可以执行以下操作。
您可以摆脱互斥对象,并使用Letter
实例作为互斥对象,这样有效地就有了4个互斥对象,每个互斥对象与Main
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()));
synchronized (toStop) {
//System.out.println(toStop.getLetter() + " spi");
// mutex.wait();
//Thread.sleep(100);
// mutex.notify();
toStop.setToGetLetter(true);
toStop.notify();
}
System.out.println(toStop.getLetter() + " spi");
Thread.sleep(100);
}
// }
for (Letter letter : letters) {
letter.kill();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void kill() {
alive = false;
}
}
在您的Letter
Thread中,您可以使用this
与Main进行协调
public class Letter implements Runnable {
private static int ID;
private char letter;
private int counter;
private boolean alive;
private volatile boolean toGetLetter = false;
public boolean isToGetLetter() {
return toGetLetter;
}
public void setToGetLetter(boolean toGetLetter) {
this.toGetLetter = toGetLetter;
}
public Letter() {
letter = (char) ('A' + ID);
alive = true;
ID++;
}
@Override
public void run() {
try {
while (alive) {
synchronized (this) {
while (!isToGetLetter()) {
this.wait();
}
System.out.println(letter + "" + counter);
counter++;
Thread.sleep((int) (Math.random() * 501 + 500));
toGetLetter = false;
this.notify();
}
}
System.out.println("Watek " + letter + " sie zakonczyl");
} catch (Exception e) {
}
}
public void kill() {
alive = false;
}
public char getLetter() {
return letter;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.