How to correctly get thread name in Java?

前端 未结 4 1350
醉酒成梦
醉酒成梦 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:11

    You are passing an instance of your DrawThread to a Thread(Runnable) constructor. It doesn't care that your class extends Thread; it only cares that it implements Runnable.

    The thread that gets started is the one created by new Thread(...)—and you didn't set the name on that one.

    In general, extending Thread is bad practice and should always be avoided. You are already almost there because you don't start the instance of your class, but pass it to a separate Thread instance.

    0 讨论(0)
  • 2021-02-04 00:17

    There are two Objects involved, the DrawThread object that contains the run method, and the new Thread created using it as the Runnable.

    this.getName obtains the name of the unstarted DrawThread. The current thread is the one you started.

    0 讨论(0)
  • 2021-02-04 00:24

    simple call:

    new DrawThread().start();
    

    to start new Thread

    DrawThread drawThread;              // declare object of class DrawThread 
    drawThread = new DrawThread();      // instantiate object of class DrawThread
    drawThread.start();                 // call start to start DrawThread
    

    (DrawThread is extending Thread class) so involves:

      public synchronized void start() {
            checkNotStarted();
    
            hasBeenStarted = true;
    
            nativeCreate(this, stackSize, daemon);   // here Thread is created 
      }
    

    u call is ike PUT THREAD INSIDE THREAD (AS RUNNABLE) by calling:

    public Thread(Runnable runnable) {
        create(null, runnable, null, 0);
    }
    
    0 讨论(0)
  • 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. :-)

    0 讨论(0)
提交回复
热议问题