java編程思想筆記---並發優先順序__編程

來源:互聯網
上載者:User
2017/7/31建立
/*   * jdk的十個優先順序與作業系統之間映射的不好,所以只推薦MAX_PRIORITY,NORM_PRIORITY,MIN_PRIORITY * 三個優先順序 */public class SimplePriorities implements Runnable {    private int countDown=5;    //禁止編譯器對變數d進行最佳化    private volatile double d;    private int priority;    public SimplePriorities(int priority){        this.priority=priority;    }    public String toString(){        return Thread.currentThread()+":"+countDown;    }    @Override    public void run() {        //線程的優先順序應該在run內設定,因為線程只有在運行後設定的優先順序才是有效        Thread.currentThread().setPriority(priority);        while (true) {            for (int i = 0; i < 10000; i++) {                //當除數為0時,程式沒有拋出異常,原因是double中的0不是真正的0或0.0 而是一個很長的                //可能是0.000000000001或其它,所以一個正數除以0.0結果就得很大很大                d+=(Math.PI+Math.E)/(double)i;                if (i%1000==0) {                    Thread.yield();                }            }            System.out.println(this);            if (--countDown==0) {                return;            }        }    }    public static void main(String[] args) {        ExecutorService exec=Executors.newCachedThreadPool();        for (int i = 0; i < 5; i++) {            exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));        }        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));        exec.shutdown();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.