获取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 红包祝福语简短10字
18 周六早晨祝福语简短