线程的常用方法——currentThread方法
Thread.currentThread()方法可以获得当前线程
Java 中的任何一段代码都是执行在某个线程当中的.
执行当前代码的线程就是当前线程.
同一段代码可能被不同的线程执行, 因此当前线程是相对的,
Thread.currentThread()方法的返回值是在代码实际运行时候的线程对象
SubThread1.java
package com.dym.juc.threadmethod;
/*
* 定义线程类
* 分别在构造方法和run方法中打印当前线程
* */
public class SubThread1 extends Thread{
public SubThread1(){
System.out.println("构造方法打印当前线程名称:"+Thread.currentThread().getName());
}
@Override
public void run() {
System.out.println("run方法打印当前线程名称:"+Thread.currentThread().getName());
}
}
Test01CurrentThread.java
package com.dym.juc.threadmethod;
public class Test01CurrentThread {
public static void main(String[] args) {
System.out.println("main方法打印当前线程名称:"+Thread.currentThread().getName());
//创建子线程,调用SubThread1()构造方法
//在main线程中调用构造方法,所以构造方法中的当前线程就是main线程
SubThread1 t1 = new SubThread1();
//启动子线程,子线程会调用run方法
//t1.start(); //run方法打印当前线程名称:Thread-0
//在main方法中直接调用run()方法,没有开启新的线程
//所以在run方法中的当前线程就是main线程
t1.run(); //run方法打印当前线程名称:main
}
}