Как я могу напечатать статус темы? - PullRequest
0 голосов
/ 18 февраля 2020

Задача: Последовательное переопределение состояния дочернего потока и печать на консоль (возможно, через промежуточное состояние): метод BLOCKED WAITING TERMINATED Thread.sleep () не используется.

Мой код:

public class Test {

private static final Object M = new Object();

  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread() {
        public void run() {
                synchronized(M) {
                    try {
                        M.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    };
    t.start();
    synchronized(M) {
        System.out.println(t.getState());
        M.notify();
        M.notifyAll(); 
}
    System.out.println(t.getState());

    System.out.println(t.getState());
    t.join();

    synchronized(M) {

        M.notify();
        M.notifyAll();
        System.out.println(t.getState());
    }
  }
}

РЕЗУЛЬТАТ:

enter image description here

Вопрос: . Помогите, как сделать так, чтобы он отображался в заданной последовательности: BLOCKED WAITING TERMINATED

1 Ответ

0 голосов
/ 18 февраля 2020

Это решение:

    public class Test {

    private static final Object M = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread() {
            public void run() {

                    try {
                        synchronized(M) {
                            M.notifyAll(); // notify before you stay on wait
                            M.wait();
                            M.notifyAll();
                            M.wait();
                            M.notifyAll();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        };
        synchronized(M) { // you need to lock M before start thread
            t.start();
            M.wait(); //wait and notifyAll need for make sure before thread t already get lock M and will blocked next time
            M.notifyAll();
            System.out.println(t.getState()); //BLOCKED
            M.wait();
            System.out.println(t.getState()); //WAITING
            M.notifyAll();

        }
        t.join();

        synchronized(M) {
            M.notifyAll();
            System.out.println(t.getState());
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...