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

BIL*_*ILL 24 java multithreading

我有这个类用于在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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

execute thread: red rectangle Thread-2
execute thread: yellow ellipse Thread-3
Run Code Online (Sandbox Code Playgroud)

我创建新线程的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么Thread.currentThread().getName()返回正确的线程名称而this.getName()返回另一个?

Gra*_*ray 51

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

你的DrawThread班级extends Thread然后通过调用启动它:

new Thread(new DrawThread(...));
Run Code Online (Sandbox Code Playgroud)

这是不正确的.这意味着创建的线程实际是一样ThreadDrawThread. DrawThread应该实现Runnable不是扩展线程.您的代码有效,因为Thread也是Runnable.

public class DrawThread implements Runnable {
Run Code Online (Sandbox Code Playgroud)

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

最后,你的课应该是DrawRunnable这样的implements Runnable.:-)


Mar*_*nik 8

您正在将您的实例传递DrawThreadThread(Runnable)构造函数.它并不关心你的课程延伸Thread; 它只关心它implements Runnable.

启动的线程是由new Thread(...)- 创建的线程- 并且您没有在该线程上设置名称.

一般来说,延伸Thread是不好的做法,应该始终避免.您已经差不多了,因为您没有start类的实例,而是将其传递给单独的Thread实例.