温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java获取线程ID的实例

发布时间:2020-10-14 10:48:23 来源:脚本之家 阅读:147 作者:知优码 栏目:开发技术

以下实例演示了如何使用 getThreadId() 方法获取线程id:

public class Main extends Object implements Runnable {
 private ThreadID var;
 
 public Main(ThreadID v) {
  this.var = v;
 }
 
 public void run() {
  try {
   print("var getThreadID =" + var.getThreadID());
   Thread.sleep(2000);
   print("var getThreadID =" + var.getThreadID());
  } catch (InterruptedException x) {
  }
 }
 
 private static void print(String msg) {
  String name = Thread.currentThread().getName();
  System.out.println(name + ": " + msg);
 }
 
 public static void main(String[] args) {
  ThreadID tid = new ThreadID();
  Main shared = new Main(tid);
 
  try {
   Thread threadA = new Thread(shared, "threadA");
   threadA.start();
 
   Thread.sleep(500);
 
   Thread threadB = new Thread(shared, "threadB");
   threadB.start();
 
   Thread.sleep(500);
 
   Thread threadC = new Thread(shared, "threadC");
   threadC.start();
  } catch (InterruptedException x) {
  }
 }
}
 
class ThreadID extends ThreadLocal {
 private int nextID;
 
 public ThreadID() {
  nextID = 10001;
 }
 
 private synchronized Integer getNewID() {
  Integer id = new Integer(nextID);
  nextID++;
  return id;
 }
 
 
 protected Object initialValue() {
  print("in initialValue()");
  return getNewID();
 }
 
 public int getThreadID() {
  Integer id = (Integer) get();
  return id.intValue();
 }
 
 private static void print(String msg) {
  String name = Thread.currentThread().getName();
  System.out.println(name + ": " + msg);
 }
}

以上代码运行输出结果为:

threadA: in initialValue()
threadA: var getThreadID =10001
threadB: in initialValue()
threadB: var getThreadID =10002
threadC: in initialValue()
threadC: var getThreadID =10003
threadA: var getThreadID =10001
threadB: var getThreadID =10002
threadC: var getThreadID =10003

以上就是Java获取线程ID的实例的详细内容,更多关于Java获取线程ID的资料请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI