以下实例演示了如何使用 getThreadId() 方法获取线程id:
Main.java 文件 public class Main extends Object { private static Runnable makeRunnable() { Runnable r = new Runnable() { public void run() { for (int i = 0; i < 5; i++) { Thread t = Thread.currentThread(); System.out.println("in run() - priority=" + t.getPriority()+ ", name=" + t.getName()); try { Thread.sleep(2000); } catch (InterruptedException x) { } } } }; return r; } public static void main(String[] args) { System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority()); System.out.println("in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName()); Thread threadA = new Thread(makeRunnable(), "threadA"); threadA.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("in main() - threadA.getPriority()="+ threadA.getPriority()); } } 以上代码运行输出结果为:
in main() - Thread.currentThread().getPriority()=5
in main() - Thread.currentThread().getName()=main
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in main() - threadA.getPriority()=5
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。