码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA并发,线程优先级

时间:2015-04-22 00:32:04      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.xt.thinks21_2;
 2 
 3 import java.util.concurrent.ExecutorService;
 4 import java.util.concurrent.Executors;
 5 
 6 /**
 7  * java线程优先级测试
 8  * 
 9  * @author Administrator
10  *
11  */
12 public class ThreadPriorityTest implements Runnable {
13     private int countDown = 5;
14     private int priority;
15     private volatile double d;
16 
17     public ThreadPriorityTest(int priority) {
18         this.priority = priority;
19     }
20 
21     @Override
22     public String toString() {
23         // TODO Auto-generated method stub
24         return Thread.currentThread() + ":" + countDown;
25     }
26 
27     @Override
28     public void run() {
29         // TODO Auto-generated method stub
30         Thread.currentThread().setPriority(priority);
31         while (true) {
32             for (int i = 0; i < 10000000; i++) {
33                 d += (Math.PI + Math.E) / (double) i;
34                 if (i % 1000 == 0)
35                     Thread.yield();
36             }
37             System.out.println(this);
38             if (--countDown == 0)
39                 return;
40         }
41     }
42 
43     public static void main(String[] args) {
44         ExecutorService es = Executors.newCachedThreadPool();
45         for (int i = 0; i < 5; i++)
46             es.execute(new ThreadPriorityTest(Thread.MIN_PRIORITY));
47         es.execute(new ThreadPriorityTest(Thread.MAX_PRIORITY));
48         es.shutdown();
49     }
50 }

线程内部执行耗时操作的时候,设置线程优先级可以有效的调整线程执行顺序(无规律)。

JAVA并发,线程优先级

标签:

原文地址:http://www.cnblogs.com/wubingshenyin/p/4445830.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!