从另一个 class 通知 java 线程

Notify java thread from another class

我有两个classes,第一个负责创建线程,然后那些线程需要从第二个通知class

问题:我找不到从第二个 class 创建的线程,getThreadByName() 总是 return null,知道吗?

头等舱

public class class1{
    protected void createThread(String uniqueName) throws Exception {

        Thread thread = new Thread(new OrderSessionsManager());
        thread.setName(uniqueName);
        thread.start();

    }
}

OrderSessionManager

public class OrderSessionsManager implements Runnable {

public OrderSessionsManager() {

}

@Override
public void run() {
    try {
        wait();
    }catch(Exception e) {
        e.printStackTrace();
    }

}

二等

public class class2{
    protected void notifyThread(String uniqueName) throws Exception {

        Thread thread = Utils.getThreadByName(uniqueName);
        thread.notify();

    }
}

实用工具

public class Utils{
    public static Thread getThreadByName(String threadName) {

        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] threads = new Thread[noThreads];
        currentGroup.enumerate(threads);
        List<String>names = new ArrayList<String>();

        for (Thread t : threads) {
            String tName = t.getName().toString();
            names.add(tName);
            if (tName.equals(threadName)) return t;
        }
    return null;
    }
}

您的代码存在几个问题:

1) 它打破了 Java Code Conventions: class 名称必须以 a 开头 大写字母

2) wait() 方法必须由拥有对象监视器的线程调用 所以你必须使用类似的东西:

 synchronized (this) {   
             wait(); 
     }

3) notify() 方法必须由拥有对象监视器的线程调用,并且由与 wait() 相同的对象调用,在您的情况下是 OrderSessionsManager 的实例。

4) 由于您没有指定 ThreadGroup,该线程从其父线程获取它的 ThreadGroup。以下代码按预期工作:

public class Main {
    public static void main(String[] args) {
        class1 c1 = new class1();
        try {
            c1.createThread("t1");
        } catch (Exception e) {
            e.printStackTrace();
        }
         Thread thread = Utils.getThreadByName("t1");
         System.out.println("Thread name " + thread.getName());
    }
}

但这只是因为 t1 线程与主线程在同一组中。