可以通过实现Runnable接口并覆盖该run()
方法来创建线程。
当前线程是Java中当前正在执行的线程对象。该方法currentThread()
Thread类的可用于获得当前线程。此方法不需要任何参数。
演示此的程序如下所示-
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