Java线程中有很多常用的方法,需要花费一些时间来理解,今天就先来学习一下currentThread()方法。
currentThread()方法返回调用此代码段的线程信息,其中可以通过 Thread.currentThread().getId()获取当前线程id
Thread.currentThread().getName()获取当前线程name
Thread.currentThread().getPriority()获取当前线程优先级

下面用代码来说明:

MyThread类

1
2
3
4
5
6
7
8
9
10
class MyThread extends Thread{
public MyThread(){
System.out.println("构造方法中打印的线程名字:"+Thread.currentThread().getName());
}
@Override
public void run() {
System.out.println("run方法中打印的线程名字:"+Thread.currentThread().getName());
}
}

CurrentThreadTest类

1
2
3
4
5
6
7
8
9
10
11
public class CurrentThreadTest {
public static void main(String[ ]args){
Thread thread=new MyThread();
thread.start();
// thread.run();
}
}

结果如下:

构造方法中打印的线程名字:main
run方法中打印的线程名字:Thread-0

说明MyThread类的构造方法被main线程调用的,run方法是自动调用的方法。

将CurrentThreadTest类改为如下:

1
2
3
4
5
6
7
8
9
10
11
public class CurrentThreadTest {
public static void main(String[ ]args){
Thread thread=new MyThread();
// thread.start();
thread.run();
}
}

结果如下:

构造方法中打印的线程名字:main
run方法中打印的线程名字:main

说明MyThread类的构造方法被main线程调用的,run方法是被main线程调用的。