我有一个静态函数,例如:
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());
}
}
}
最佳答案
您已经显示了调用您的代码的线程的名称。证明这一点的代码:
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
您的问题在于未显示的代码。
- 要么您的方法被一个且只有一个线程调用,要么
- 或者您为所有线程指定相同的名称。
同样,要获得关于当前设置实际问题的完整解决方案,请创建并发布 sscce类似于我上面发布的内容。据我们所知,您可能会在您的线程上调用 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。
但同样,您的代码也证明您的线程名称 *are8 正在显示,但您只能看到一个名称,可能是因为该线程正在占用 CPU。
关于java - 识别访问静态代码块的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18948732/