Home » Java » java – How i can print thread status?-Exceptionshub

java – How i can print thread status?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Task:
Sequentially override the state of the child stream and print to the console (possibly through an intermediate state): BLOCKED WAITING TERMINATED method Thread.sleep () not to use.

My code:

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

RESULT:

enter image description here

Question:
Pls help how to make it appear in the given sequence: BLOCKED WAITING TERMINATED

How to&Answers:

This is solution:

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