如何在Java中正确获取线程名称? [英] How to correctly get thread name in Java?
问题描述
我有这个类用于在Java中创建一个线程
I have this class for creating a thread in Java
package org.vdzundza.forms;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class DrawThread extends Thread {
private static final int THREAD_SLEEP = 500;
public CustomShape shape;
private Graphics g;
public DrawThread(CustomShape shape, Graphics g) {
this.shape = shape;
this.g = g;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(THREAD_SLEEP);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(this.shape.getColor());
g2d.fill(this.shape.getShape());
System.out.println(String.format("execute thread: %s %s",
Thread.currentThread().getName(), this.getName()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
console将以下文本显示为输出
The console displays the following text as an output
execute thread: red rectangle Thread-2
execute thread: yellow ellipse Thread-3
创建新主题的代码:
customShapes[0] = new CustomShape(
new Rectangle2D.Float(10, 10, 50, 50), Color.RED,
"red rectangle");
customShapes[1] = new CustomShape(new Ellipse2D.Float(70, 70, 50, 50),
Color.YELLOW, "yellow ellipse");
for (CustomShape cshape: customShapes) {
Thread t = new Thread(new DrawThread(cshape, this.getGraphics()),
cshape.getName());
threads.add(t);
t.start();
}
我的问题是:为什么 Thread.currentThread( ).getName()
返回正确的线程名称,而 this.getName()
返回另一个?
My Question is: Why does Thread.currentThread().getName()
return the correct thread name whilst this.getName()
returns another?
推荐答案
为什么
Thread.currentThread()。getName()
返回正确的线程名称,而this.getName()
返回其他?
Why
Thread.currentThread().getName()
return correct thread name whilstthis.getName()
return other?
您的 DrawThread
class extends Thread
但是你通过调用启动它:
Your DrawThread
class extends Thread
but then you start it by calling:
new Thread(new DrawThread(...));
这是不正确的。这意味着从 DrawThread
创建的实际线程不相同的线程
。 DrawThread
应该实现 Runnable
和不扩展线程。您的代码有效,因为Thread也是Runnable。
This is not correct. It means that the actual thread that is created is not the same Thread
from DrawThread
. DrawThread
should be implementing Runnable
and not extending thread. Your code works because Thread is also a Runnable.
public class DrawThread implements Runnable {
因为有两个线程对象,当你在 DrawThread $ c上调用
this.getName()
时$ c>对象不是实际运行的线程,因此其名称未正确设置。仅设置包装线程的名称。在 DrawThread
代码中,您应该调用 Thread.currentThread()。getName()
来获取真实的名称正在运行的线程。
Because there are two thread objects, when you call this.getName()
on the DrawThread
object that is not the thread that is actually running so its name is not properly set. Only the wrapping thread's name is set. Inside of the DrawThread
code, you should call Thread.currentThread().getName()
to get the true name of the running thread.
最后,你的类应该是 DrawRunnable
如果实现了Runnable
。 : - )
Lastly, your class should probably be DrawRunnable
if it implements Runnable
. :-)
这篇关于如何在Java中正确获取线程名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!