1.3currentThread方法
currentThread()方法可以返回段正在被哪个线程调用的信息。
示例代码:
public class Main { public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); } }
结果:说明main()被名为main的线程调用。
public class OneThread extends Thread { public OneThread() { System.out.println("构造方法的打印: " + Thread.currentThread().getName()); } @Override public void run() { System.out.println("run方法的打印:" + Thread.currentThread().getName()); } }
执行方法:
public class Main { public static void main(String[] args) { OneThread ot = new OneThread(); ot.start(); } }
结果:
若执行方法为:
public class Main { public static void main(String[] args) { OneThread ot = new OneThread(); ot.run();//注意此处调用的是run(),我们曾提过,调用run()相当于将run()交给其他线程来完成 } }
更复杂的示例:
public class TwoThread extends Thread { public TwoThread() { System.out.println("Count-Operate--begin"); System.out.println("Thread.currentThread().getName()= " + Thread.currentThread().getName()); System.out.println("this.getName()= " + this.getName()); System.out.println("Count-Operate--end"); } @Override public void 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 class Main { public static void main(String[] args) { TwoThread tt = new TwoThread(); Thread t = new Thread(tt); t.setName("A"); t.start(); } }
根据结果逆向分析:Thread.currentThread().getName()获得的始终是主线程(也就是说由JVM创建的main线程)。
而由对象本身调用的getName()获取的都是打开的第二个线程Thread-0,也就是执行start()方法的线程。
现在分析发现这个思考是有问题的。
Thread.currentThread().getName()获得的始终是执行start()方法的线程(或者说是调用run()方法的线程)。
而this.getName()获得的都是run()方法所在线程对象的名称。
源码地址:https://github.com/lilinzhiyu/threadLearning
赞赏
长按二维码向我转账
受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。
已发送
发送中
微信扫一扫关注该公众号