Home  >  Q&A  >  body text

Java多线程Thread.currentThread()的疑问

高洛峰高洛峰2722 days ago794

reply all(4)I'll reply

  • PHPz

    PHPz2017-04-18 10:03:15

    Thread.currentThread() does not return the thread in which the current program is running, but returns the thread in which the code Thread.currentThread() is executed.

    So you can see that when the new thread is constructed, the code is executed in the main thread, while the code in the run method is executed in the thread.

    It’s easy to understand by looking at the output

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:03:15

    1. new一个Thread对象的时候默认的名字就是Thread-n格式的,你可以看看Thread源码。
    2、你这就是一个线程对象,this在你这样使用的情况下,是当前的线程了。
    3、Thread.currentThread()Always returns the currently running thread.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:03:15

    The running result of the constructor method is understandable, but why is the running result of the run method not testThread in setName but thread?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:03:15

    1. The getName() method is inherited from the Thread class. Just look at the getName() method of the Thread class:

        /**
         * Returns this thread's name.
         *
         * @return  this thread's name.
         * @see     #setName(String)
         */
        public final String getName() {
            return String.valueOf(name);
        }

    2.Yes
    3.Yes
    In the constructor, Thread.currentThread() is the main thread, and Thread.currentThread() in the run method is the current thread

    reply
    0
  • Cancelreply