从另一个类通知java线程

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


问题:我无法从第二个类中找到创建的线程,getThreadByName() 总是返回 null,Any Idea?。


头等舱


public class class1{

    protected void createThread(String uniqueName) throws Exception {


        Thread thread = new Thread(new OrderSessionsManager());

        thread.setName(uniqueName);

        thread.start();


    }

}

订单会话管理器


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;

    }

}


芜湖不芜
浏览 325回答 1
1回答

交互式爱情

您的代码有几个问题:1) 它打破了 Java 代码约定:类名必须以大写字母开头2) wait() 方法必须由拥有对象监视器的线程调用,因此您必须使用以下内容:&nbsp;synchronized (this) {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;wait();&nbsp;&nbsp; &nbsp; &nbsp;}3)notify() 方法必须由拥有对象监视器的线程和与 wait() 相同的对象调用,在您的情况下是 OrderSessionsManager 的实例。4) 由于您没有指定 ThreadGroup,线程从它的父线程获取它的 ThreadGroup。以下代码按预期工作:public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; class1 c1 = new class1();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c1.createThread("t1");&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Thread thread = Utils.getThreadByName("t1");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Thread name " + thread.getName());&nbsp; &nbsp; }}但这只是因为t1线程与主线程在同一组中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java