How to correctly get thread name in Java?

前端 未结 4 1439
醉酒成梦
醉酒成梦 2021-02-03 23:38

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 exten         


        
4条回答
  •  忘掉有多难
    2021-02-04 00:31

    Why Thread.currentThread().getName() return correct thread name whilst this.getName() return other?

    Your DrawThread class extends Thread but then you start it by calling:

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

    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 {
    

    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.

    Lastly, your class should probably be DrawRunnable if it implements Runnable. :-)

提交回复
热议问题