我有一个静态函数,比如:
public static void foo()
{
//code follows
System.out.println(Thread.currentThread().getName());
//code follows
}多个线程同时调用此函数。我已经将线程名称设置为
Thread.setName(String)当我执行代码时,print语句将只打印一个线程的名称。如何标识当前执行foo()函数的所有线程的名称?
编辑:
public class FooThread extends Thread
{
public FooThread(String name)
{
this.setName(name);
}
@Override public void run()
{
//do something
//do something
Main.foo();
}
}
//Main Class
public class Main
{
public static void main(String[] args)
{
for(int i=0;i<6;++i)
{
new FooThread("Thread"+i).start();
}
}
public static void foo()
{
//do something
while(true)
{
//do something
System.out.println(Thread.currentThread().getName());
}
}
}发布于 2013-09-22 21:11:23
您已经显示了调用代码的线程的名称。证明这一点的代码:
public class Foo2 {
public static synchronized void foo() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
int maxCount = 10;
for (int i = 0; i < maxCount; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
foo();
}
});
thread.setName("Thread " + i);
thread.start();
long sleepTime = 1000;;
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
}
}返回:
Thread 0
Thread 1
Thread 2
Thread 3
Thread 4
Thread 5
Thread 6
Thread 7
Thread 8
Thread 9您的问题在于没有显示代码。
同样,关于当前设置的实际问题的完整解决方案,请创建并发布一个类似于我上面发布的斯考斯。据我们所知,您可以在线程上调用run(),在我们看到并再现您的问题之前,我认为我们将无法完全理解它。
编辑
关于SSCCE:比较下面两个方法的结果,foo1()和foo2()
class FooThread extends Thread {
public FooThread(String name) {
this.setName(name);
}
@Override
public void run() {
// do something
// do something
Main.foo1(); // !! Swap comments
// Main.foo2(); // !! Swap comments
}
}
// Main Class
public class Main {
private static final long SLEEP_TIME = 4;
public static void main(String[] args) {
for (int i = 0; i < 6; ++i) {
new FooThread("Thread" + i).start();
}
}
public static void foo1() {
// do something
while (true) {
// do something
synchronized (Main.class) {
System.out.println(Thread.currentThread().getName());
}
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {}
}
}
public static void foo2() {
while (true) {
System.out.println(Thread.currentThread().getName());
}
}
}如果while循环不是很紧,但是使用一个短的Thread.sleep来产生CPU,那么您将看到更多的不同线程在更近的地方共享foo。
但是,您的代码还证明您的线程名称*正在显示,但是您只看到一个名称,因为线程占用了CPU。
发布于 2013-09-22 21:13:09
另一种选择是获取所有线程堆栈并查找foo()中的所有线程--除了捕获您想要的信息之外,它没有开销或额外代码的好处。
顺便说一句:你能说得更清楚吗?为什么你需要这些信息,因为我怀疑有更好的方法来做你真正想要的事情?
发布于 2013-09-22 21:06:16
如果您只想获得线程数,请使用线程安全计数器来存储线程数。在foo()开始时增加计数器,当foo()退出时减少计数器。
如果需要获取名称,请使用散列集(如果有线程名称的重复项)来存储名称:在foo()开始时添加名称,并在foo()退出时删除名称。确保对哈希集的访问是线程安全的。您还需要另一个方法来打印哈希集的内容,因此您可以随时调用它来查看执行foo()的线程的名称。
https://stackoverflow.com/questions/18948732
复制相似问题