gpt4 book ai didi

java - 从另一个类通知java线程

转载 作者:行者123 更新时间:2023-12-02 10:40:29 25 4
gpt4 key购买 nike

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

问题:我找不到从第二个类创建的线程,getThreadByName() 总是返回 null,有什么想法吗?

头等舱

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

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

}
}

订单 session 管理器

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 : 类名必须以 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 线程与主线程位于同一组中。

关于java - 从另一个类通知java线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52943672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com