获取Java中的当前线程
可以通过实现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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短