在Java中获取线程ID
时间:2020-02-23 14:34:14 来源:igfitidea点击:
在本文中,我们将学会获得线程 idJava中的一个正在运行的线程。
一个 Id是在创建线程时生成的独特正数。
此ID在线程的寿命期间保持不变。
当线程终止时,它的ID可用于引用另一个线程,但两个线程不能相同 id数字同时。
要获取线程ID,Java Thread类提供了一种方法
getId()返回长型值 id数字。
该方法的语法如下:
public long getId()
在Java中获取线程ID
在此示例中,我们创建并启动了一个线程。
之后,通过使用 getId()方法,我们获得线程ID。
请参阅下面的示例。
public class Main
{
public static void main(String args[])
{
Thread thread = new Thread();
thread.start();
try {
for (int i = 0; i < 5; i++) {
System.out.println(i);
Thread.sleep(500);
}
}catch(Exception e) {
System.out.println(e);
}
//get thread id
long id = thread.getId();
System.out.println("Thread id : "+id);
}
}
输出
0 1 2 3 4 Thread id : 11
获取当前运行线程的线程ID
如果我们想获取当前runnig线程的id,那么通过使用 currentThread()我们可以调用的方法 getId()方法。
请参阅下面的示例。
public class Main
{
public static void main(String args[])
{
Thread thread = new Thread();
thread.start();
try {
for (int i = 0; i < 5; i++) {
System.out.println(i);
Thread.sleep(500);
}
}catch(Exception e) {
System.out.println(e);
}
//get current thread id
long id = Thread.currentThread().getId();
System.out.println("Thread id : "+id);
id = thread.getId();
System.out.println("Thread id : "+id);
}
}
输出
0 1 2 3 4 Thread id : 1 Thread id : 11
获取多个线程的线程ID
Java允许创建多个线程,在这种情况下,我们可以通过调用getID()方法来获得个体威胁的威胁ID。
请参阅下面的示例。
public class Main
{
public static void main(String args[])
{
Thread thread1 = new Thread();
Thread thread2 = new Thread();
Thread thread3 = new Thread();
thread1.start();
thread2.start();
thread3.start();
try {
for (int i = 0; i < 5; i++) {
System.out.println(i);
Thread.sleep(500);
}
}catch(Exception e) {
System.out.println(e);
}
//get current thread id
long id = thread1.getId();
System.out.println("Thread1 id : "+id);
id = thread2.getId();
System.out.println("Thread2 id : "+id);
id = thread3.getId();
System.out.println("Thread3 id : "+id);
}
}
输出
0 1 2 3 4 Thread1 id : 11 Thread2 id : 12 Thread3 id : 13

