在 Java 中获取当前线程
java 8object oriented programmingprogramming
可以通过实现 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