从另一个类通知 java 线程



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

问题:我找不到从第二个类中创建的线程,getThreadByName(( 总是返回 null,任何想法?。

头等舱

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

您的代码存在几个问题:

1(它打破了Java代码约定:类名必须以 大写字母

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

synchronized (this) {   
wait(); 
}

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

4( 由于您没有指定线程组,因此线程从其父线程获取其线程组。以下代码按预期工作:

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线程与主线程位于同一组中。

最新更新