我有两个类,第一个负责创建线程,然后需要从第二个类通知这些线程
问题:我无法从第二个类中找到创建的线程,getThreadByName()总是返回null,任何想法?。
FirstClass
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();
}
}
SecondClass
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;
}
}
答案 0 :(得分:0)
您的代码有几个问题:
1)打破Java Code Conventions:类名必须以 大写字母
2)wait()方法必须由拥有对象监视器的线程调用 所以您必须使用类似的东西:
synchronized (this) {
wait();
}
3)必须由拥有对象的监视器的线程以及与wait()相同的对象(在您的情况下为OrderSessionsManager的实例)中调用notify()方法。
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 线程与主线程位于同一组中。