【问题标题】:How to make random thread wait then wake it up after constant time如何让随机线程等待然后在恒定时间后唤醒它
【发布时间】:2015-07-28 21:40:01
【问题描述】:

在我的主线程中,我创建并启动了四个线程 (A,B,C,D),它们每 500 到 1000 毫秒在控制台上打印字母和数字。 比如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
    }
}

【问题讨论】:

  • 您在mutex 上进行同步,并在toStop 上调用wait()。你应该打电话给mutex.wait()
  • @NitinDandriyal 但我想暂停toStop,直到我调用通知。
  • @NitinDandriyal 我更新了run 中的Main 线程永无止境。我添加了StopTask,所以现在复制的代码将编译并运行。
  • 您必须首先了解,要对任何对象调用等待和通知,您必须首先使用synchronized 关键字获取该对象的监视器,否则您将得到此异常。请牢记这一点,重新编写代码。
  • 目前你的mutex 只对主线程可见,其余的Letter 线程不知道也不关心它,因此没有意义等待并通知当前代码的主线程

标签: java multithreading wait notify


【解决方案1】:

您的代码示例不起作用,因为在没有拥有对象监视器的情况下进行了 wait() 调用。

这里是 javadoc 的解释: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()

这是来自 javadoc 的 sn-p:

公共最终无效等待() 抛出 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

【讨论】:

  • 您应该始终在答案中附加重要的代码 sn-p,因为链接可能无法正常工作或可能被删除,因此 sn-ps 工作
  • 请查看修改后的代码。这些字母永远不会停止打印。
【解决方案2】:

这是一个典型的生产者-消费者问题,有更好的方法来解决。由于我们正在解决手头的问题,您可以在下面做。

您可以摆脱互斥对象并将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 线程中,您可以使用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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多