根据线程名称找到线程,在java中是可以实现的,实现步骤是:1、首先获取Java VM中当前运行的所有线程以下代码是用数组返回Java VM中当前运行的所有线程 public static Thread[] findAllThreads(){ ThreadGroup group = Thread.currentThread().getThreadGroup(); ThreadGroup topGroup = group; /...
java 根据线程名字查询一个线程,能实现吗?
public class EegExp {
public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
// System.out.println(Thread.currentThread().getName());
}
}
}, "1").start();
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
// System.out.println(Thread.currentThread().getName());
}
}
}, "2").start();
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
// System.out.println(Thread.currentThread().getName());
}
}
}, "2").start();
new JFrame().setVisible(true);
int n = Thread.activeCount();
Thread[] threads = new Thread[n];
Thread.enumerate(threads);
boolean b = false;
for (int i = 0; i < threads.length; i++) {
Thread thread = threads[i];
if (thread.getName().equals("test")) {
b = true;
}
}
if (!b) {
JOptionPane.showMessageDialog(null, "没有找到线程即将启动");
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
System.out.println(Thread.currentThread().getName());
}
}
}, "test").start();
}
}
}2011-03-25
根据线程名称找到线程,在java中是可以实现的,实现步骤是:1、首先获取Java VM中当前运行的所有线程以下代码是用数组返回Java VM中当前运行的所有线程
public static Thread[] findAllThreads(){ ThreadGroup group = Thread.currentThread().getThreadGroup(); ThreadGroup topGroup = group; /* 遍历线程组树,获取根线程组 */ while ( group != null ) { topGroup = group; group = group.getParent(); } /* 激活的线程数加倍 */ int estimatedSize = topGroup.activeCount() * 2; Thread[] slackList = new Thread[estimatedSize]; /* 获取根线程组的所有线程 */ int actualSize = topGroup.enumerate( slackList ); /* copy into a list that is the exact size */ Thread[] list = new Thread[actualSize]; System.arraycopy( slackList, 0, list, 0, actualSize ); return (list);}2、遍历线程,比对名称,找到需要寻找的线程以下代码可得到线程的名称
String name = thread.getName();2015-07-10
用callable接口,回调信息2011-03-25
看一楼2011-03-25