代码之家  ›  专栏  ›  技术社区  ›  Victor Grazi

当线程改变状态时,有没有办法在进程中获取通知?

  •  1
  • Victor Grazi  · 技术社区  · 7 年前

    当线程改变状态时,有没有办法在进程中获取通知?我正在编写一个程序来监视线程状态的变化。我可以经常调查每个帖子,但我更喜欢反应性更强的帖子。

    2 回复  |  直到 7 年前
        1
  •  1
  •   宏杰李    7 年前

    是的,使用 conditional variable ,以下是一个例子:

    import java.util.concurrent.locks.*;
    public class CubbyHole2 {
        private int contents;
        private boolean available = false;  // this is your state
        private Lock aLock = new ReentrantLock(); // state must be protected by lock
        private Condition condVar = aLock.newCondition(); // instead of polling, block on a condition
    
        public int get(int who) {
            aLock.lock();  
            try {
                // first check state
                while (available == false) {
                    try {
                        // if state not match, go to sleep
                        condVar.await(); 
                    } catch (InterruptedException e) { }
                }
                // when status match, do someting
    
                // change status
                available = false;
                System.out.println("Consumer " + who + " got: " +
                                    contents);
                // wake up all sleeper than wait on this condition
                condVar.signalAll();  
            } finally {
                aLock.unlock();
                return contents;
            }
        }
    
        public void put(int who, int value) {
                        aLock.lock();
        try {
            while (available == true) {
                try {
                    condVar.await();
                } catch (InterruptedException e) { }
            }
            contents = value;
            available = true;
            System.out.println("Producer " + who + " put: " +
                                contents);
            condVar.signalAll();
            } finally {
                aLock.unlock();
            }
        }
    }
    
        2
  •  0
  •   Peter Lawrey    7 年前

    线程运行的代码需要注入代码,以便在状态发生变化时进行回调。你可以按照@的建议更改代码,或者在代码中注入 Instrumentation 然而,轮询线程可能是最简单的。

    注意:从JVM的角度来看,线程的状态只告诉您它是所需的状态。它没有告诉你

    • 它被阻塞IO操作阻塞了吗?
    • 它被上下文切换了吗
    • 它是否被操作系统或BIOS中断
    • 是否因GC或代码替换而停止
    • 它正在等待静态初始化程序块上的锁。e、 g.如果它在等待类初始化时被阻止,则表示它正在运行。

    顺便说一句,即使是操作系统也会轮询CPU以查看它们在做什么,通常每秒轮询100次。