• Java如何获取正在运行的线程的Id?


    在Java编程中,如何获取正在运行的线程的Id?

    以下示例演示如何使用getThreadId()方法获取正在运行的线程的Id。

    package com.yiibai;
    
    public class IdThread extends Object implements Runnable {
        private ThreadID var;
    
        public IdThread(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();
            IdThread shared = new IdThread(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);
        }
    }
    
    Java

    上述代码示例将产生以下结果 -

    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
  • 相关阅读:
    map
    01背包和完全背包 POJ
    并查集 计算节点数量
    set
    map,vector,queue 图 综合运用
    并查集 hdu-1325 Is It A Tree?
    js中的ajax
    java算法
    MySql在Window上的安装
    微信开发账号要求
  • 原文地址:https://www.cnblogs.com/borter/p/9613451.html
Copyright © 2020-2023  润新知