zoukankan      html  css  js  c++  java
  • currentThread()方法返回代码段正在被哪个线程调用

    currentThread()方法返回代码段正在被哪个线程调用

    package com.stono.thread2.page16;
    
    public class MyThread extends Thread{
        public MyThread() {
            System.out.println("构造方法的打印:"+Thread.currentThread().getName());
        }
        @Override
        public void run() {
            System.out.println("run方法的打印:"+Thread.currentThread().getName());
        }
        
        public static void main(String[] args) {
            MyThread myThread = new MyThread();
    //        myThread.start();
    //        构造方法的打印:main
    //        run方法的打印:Thread-0
    
            myThread.run();
    //        构造方法的打印:main
    //        run方法的打印:main
    
        }
    }

     注意与this.getName()的区别

    package com.stono.thread2.page16;
    
    public class CountOperate extends Thread{
        public CountOperate() {
            System.out.println("CountOperate---begin");
            System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
            System.out.println("this.getName()="+this.getName());
            System.out.println("CountOperate---end");
        }
        @Override
        public void run() {
            // super.run();
            System.out.println("run---begin");
            System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
            System.out.println("this.getName()="+this.getName());
            System.out.println("run---end");
            
        }
        
        public static void main(String[] args) {
            CountOperate c = new CountOperate();
            Thread t1 = new Thread(c);
            t1.setName("A");
            t1.start();
    //    CountOperate---begin
    //    Thread.currentThread().getName()=main
    //    this.getName()=Thread-0
    //    CountOperate---end
    //    run---begin
    //    Thread.currentThread().getName()=A
    //    this.getName()=Thread-0
    //    run---end
        }
    
    }

     this.getName()是Thread.getName()方法,源码:

        public final String getName() {
            return new String(name, true);
        }
  • 相关阅读:
    CodeForces Gym 100935G Board Game DFS
    CodeForces 493D Vasya and Chess 简单博弈
    CodeForces Gym 100935D Enormous Carpet 快速幂取模
    CodeForces Gym 100935E Pairs
    CodeForces Gym 100935C OCR (水
    CodeForces Gym 100935B Weird Cryptography
    HDU-敌兵布阵
    HDU-Minimum Inversion Number(最小逆序数)
    七月馒头
    非常可乐
  • 原文地址:https://www.cnblogs.com/stono/p/8370699.html
Copyright © 2011-2022 走看看