Home > Java > javaTutorial > body text

Java example - get thread id

黄舟
Release: 2016-12-27 13:34:53
Original
1756 people have browsed it

The following example demonstrates how to use the getThreadId() method to obtain the thread id:

/*
 author by w3cschool.cc
 Main.java
 */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);
  }}
Copy after login

The output result of the above code is:

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
Copy after login

The above is the Java example-get The content of the thread id, please pay attention to the PHP Chinese website (www.php.cn) for more related content!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template