在 Java 中获取当前线程
可以通过实现 Runnable 接口并重写 run() 方法创建线程。
当前线程是 Java 中当前执行的线程对象。Thread 类的 currentThread() 方法可用于获取当前线程。此方法不需要任何参数。
演示此内容的程序如下所示 −
示例
public class Demo extends Thread { public void run() { for (int i = 0; i < 5; i++) { System.out.println("The Thread name is " + Thread.currentThread().getName()); } } public static void main(String[] args) { Demo t1 = new Demo(); t1.setName("Main Thread"); t1.start(); Thread t2 = currentThread(); t2.setName("Current Thread"); for (int i = 0; i < 5; i++) { System.out.println("The Thread name is " + t1.currentThread().getName()); } } }
输出
上述程序输出如下 −
The Thread name is Current Thread The Thread name is Current Thread The Thread name is Current Thread The Thread name is Current Thread The Thread name is Current Thread The Thread name is Main Thread The Thread name is Main Thread The Thread name is Main Thread The Thread name is Main Thread The Thread name is Main Thread
广告