Thread.currentThread() 方法
Thread.currentThread() 方法可以返回调用当前代码块的线程的信息。1
2
3
4
5
6
7
8
9
10
11
12
13
14public class CustomThread extends Thread {
public CustomThread() {
super();
System.out.println("构造方法:" + Thread.currentThread().getName());
}
public synchronized void run() {
super.run();
System.out.println("run() 方法:" + Thread.currentThread().getName());
}
}
1 | public class CustomThreadTest { |
Thread.currentThread() 方法可以返回是什么线程调用了CustomThread的构造方法,什么线程调用了CustomThread的run()方法:1
2构造方法:main
run() 方法:Thread-0
main 线程调用了CustomThread的构造方法,一个名叫Thread-0的线程调用了CustomThread的run()方法(若线程没有指定名称,则会默认生成一个名称)
Thread.currentThread().getName() 方法与 this.getName() 方法
1 | public class CustomThread extends Thread { |
1 | public class CustomThreadTest { |
输出:1
2
3
4构造方法:main
构造方法:Thread-0
run() 方法:Thread-0
run() 方法:Thread-0
可以发现this.getName() 方法两个结果是一样的,因为this实际是指代当前被调用的类实例是哪个:
当构造方法被调用时,main线程调用了CustomThread类实例,当run()方法被调用时,Thread-0 线程调用了CustomThead类实例
isAlive() 方法
isAlive() 方法可以判断当前的线程是否处于活动状态。1
2
3
4
5
6
7
8
9public class CustomThread extends Thread {
public synchronized void run() {
super.run();
System.out.println("run() 方法:" + this.isAlive());
}
}
1 | public class CustomThreadTest { |
输出:1
2
3before start:false
before end:true
run() 方法:true
若调用 main 线程调用customThread 执行 start() 方法后休眠一会:1
2
3
4
5
6
7
8
9
10public class CustomThreadTest {
public static void main(String[] args) throws InterruptedException {
CustomThread customThread = new CustomThread();
System.out.println("before start:" + customThread.isAlive());
customThread.start();
Thread.sleep(1000);
System.out.println("before end:" + customThread.isAlive());
}
}
输出:1
2
3before start:false
run() 方法:true
before end:false
因为经过休眠,customThread 线程已经执行完毕了
sleep() 方法
sleep() 方法的作用是在指定的毫秒数内让当前正在执行的线程休眠。
可参考上述例子。
getId() 方法
获取线程的唯一标识
setName() 方法
设置线程的名称
getName() 方法
获取线程的名称