一尘不染

如何正确获取Java中的线程名称?

java

我有用于在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();
            }
        }
    }
}

控制台显示以下文本作为输出

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()返回另一个?


阅读 220

收藏
2020-12-03

共1个答案

一尘不染

为什么要Thread.currentThread().getName()返回正确的线程名称而又this.getName()返回其他?

您的DrawThread课程,extends Thread但随后您通过调用以下内容开始:

new Thread(new DrawThread(...));

这是不正确的。这意味着创建的线程实际是 一样ThreadDrawThreadDrawThread应该实现Runnable
不是 扩展线程。您的代码可以工作,因为线程也是可运行的。

public class DrawThread implements Runnable {

因为有两个线程对象,所以当您调用this.getName()DrawThread对象不是实际运行的线程时,因此其名称设置不正确。仅设置包装线程的名称。在DrawThread代码内部,应调用Thread.currentThread().getName()以获取运行线程的真实名称。

最后,你的类也许应该是DrawRunnable,如果它implements Runnable。:-)

2020-12-03