获取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
热门推荐
2 薛之谦祝福语简短
7 甄嬛传祝福语简短
10 生日祝福语男孩 简短独特
11 中秋祝福语给父亲简短
12 简短正能量生日祝福语
13 老考试顺利祝福语简短
14 忙碌生活祝福语简短英文
15 生日祝福语古朴简短独特
16 科研文案祝福语简短励志
17 双十一祝福语大全简短
18 新婚红包祝福语简短男