Java 实例 - 查看线程优先级


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

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

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

  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