一、currrentThread介绍
(1)Thread.currentThread()方法用于获取对当前线程的引用。Thread.currentThread()是Thread的一个静态方法,用来获取当前线程对象的一个引用。
(2)在Java中,Thread.currentThread()
方法提供了一个访问当前执行线程的方式。这个方法返回一个Thread
对象,该对象代表调用此方法的线程。通过这个方法,可以获取当前线程的各种属性,如线程名称、优先级、是否为守护线程等,并且可以对这些属性进行修改。
例如:
通过Thread.currentThread().setName()
来更改线程的名称,
通过Thread.currentThread().isInterrupted()
来检查线程是否被中断。
(3)此外,Thread.currentThread().interrupt()
方法用于中断当前线程。当调用此方法时,当前线程的中断状态会被设置,如果线程处于阻塞状态(如调用sleep()
、wait()
、join()
等方法),那么调用interrupt()
方法将会抛出InterruptedException
异常并清除中断状态。
二、案例
public class Demo {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt).start();
new Thread(mt, "Name1").start();
new Thread(mt, "Name2").start();
System.out.println(Thread.currentThread().getName()); // main主方法
// System.out.println(this.getName()); // this获取不到线程对象
}
}
class MyThread extends Thread {@Override public void run() {
try {
Thread.sleep(3000);
Thread t = Thread.currentThread();
System.out.println("当前线程名字:" + t.getName() + " 当前线程的优先级别为:" + t.getPriority() + " ID:" + t.getId());
// System.out.println("当前线程名字:" + this.getName() + " 当前线程的优先级别为:" + this.getPriority() + " ID:"+ this.getId());
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
三、总结
1. Thread提供静态方法currentThread()来供我们调用,既可以避免this无法获取到main线程的问题,又可以避免this无法获取到Thread t2=new Thread(Thread t)来开启的线程的问题,可以说currentThread方法可以在所有场合获取到正确的当前线程。
2. 在自定义线程类时,如果线程类是继承java.lang.Thread的话,那么线程类就可以使用this关键字去调用继承自父类Thread的方法,this就是当前的对象。
3. Thread.currentThread()可以获取当前线程的引用,一般都是在没有线程对象又需要获得线程信息时通过Thread.currentThread()获取当前代码段所在线程的引用。