我有两个类,第一个负责创建线程,然后需要从第二个类通知那些线程
问题:我无法从第二个类中找到创建的线程,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;
}
}
交互式爱情
相关分类