java - 我如何打印线程状态?

标签 java multithreading java-threads

任务: 依次覆盖子流的状态并打印到控制台(可能通过中间状态):BLOCKED WAITING TERMINATED method Thread.sleep() not to use.

我的代码:

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

最佳答案

这是解决方案:

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

关于java - 我如何打印线程状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60286826/

相关文章:

c# - 如何在 Form 的关闭事件中停止 BackgroundWorker?

java - 在Java中创建另一个任务时取消当前任务并重用同一线程

c# - 什么时候(不)两个具有相同内容的字符串共享相同的内存?

java - Libgdx 非缩放全屏

java - 无法在 IntelliJ 中进入 Debug模式的方法?

java - Java中CompletableFuture如何进行资源清理?

java - 了解Java线程干扰

java - 优化循环更新请求

java - 如何在java中添加try和catch

c - 使用 swapcontext() 或 getcontext() & setcontext() 为线程库编写 yield() 函数