Java 实例 - 查看线程优先级

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

Main.java 文件

  1. public class Main extends Object {
  2. private static Runnable makeRunnable() {
  3. Runnable r = new Runnable() {
  4. public void run() {
  5. for (int i = 0; i < 5; i++) {
  6. Thread t = Thread.currentThread();
  7. System.out.println("in run() - priority="
  8. + t.getPriority()+ ", name=" + t.getName());
  9. try {
  10. Thread.sleep(2000);
  11. }
  12. catch (InterruptedException x) {
  13. }
  14. }
  15. }
  16. };
  17. return r;
  18. }
  19. public static void main(String[] args) {
  20. System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority());
  21. System.out.println("in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName());
  22. Thread threadA = new Thread(makeRunnable(), "threadA");
  23. threadA.start();
  24. try {
  25. Thread.sleep(3000);
  26. }
  27. catch (InterruptedException x) {
  28. }
  29. System.out.println("in main() - threadA.getPriority()="+ threadA.getPriority());
  30. }
  31. }

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

  1. in main() - Thread.currentThread().getPriority()=5
  2. in main() - Thread.currentThread().getName()=main
  3. in run() - priority=5, name=threadA
  4. in run() - priority=5, name=threadA
  5. in main() - threadA.getPriority()=5
  6. in run() - priority=5, name=threadA
  7. in run() - priority=5, name=threadA
  8. in run() - priority=5, name=threadA