java線程入門一

來源:互聯網
上載者:User

標籤:通過   unit   for   log   static   忽略   priority   add   執行   

線程優先順序:

在JAVA線程中,通過一個int型變數priority來控制線程優先順序,線程的有限機為1-10,預設為5,優先順序高的線程獲得的已耗用時間要高於優先順序低的線程。但這隻是一個提示,作業系統和JVM可能會根據自身情況忽略這個情況。請看下面代碼:

import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeUnit;public class Priority {    private static volatile boolean notStart=true;    private static volatile boolean notEnd=true;    public static void main(String[] args) throws Exception{        List<Job> jobs=new ArrayList<>();        for(int i=0;i<10;++i){            int priority=i<5?Thread.MIN_PRIORITY:Thread.MAX_PRIORITY;            Job job=new Job(priority);            jobs.add(job);            Thread thread=new Thread(job,"Thread"+i);            thread.setPriority(priority);            thread.start();            //thread.setPriority(188);  優先順序超出1-10,這個範圍時,運行期會拋異常;        }        notStart=false;        TimeUnit.SECONDS.sleep(10);        notEnd=false;        for(Job job:jobs){            System.out.println("Job Priority:"+job.priority+",Conut:"+job.jobCount);        }    } private  static class Job implements Runnable{        private int priority;        private long jobCount;                                                    public Job(int priority) {         this.priority = priority;     }     public void run() {                                                    while(notStart){             Thread.yield();         }         while (notEnd){             Thread.yield();             jobCount++;         }     }                      }

執行結果如下:

Job Priority:1,Conut:4665639
Job Priority:1,Conut:4814788
Job Priority:1,Conut:4783102
Job Priority:1,Conut:5667441
Job Priority:1,Conut:4688465
Job Priority:10,Conut:4618501
Job Priority:10,Conut:5598076
Job Priority:10,Conut:5212791
Job Priority:10,Conut:5627112
Job Priority:10,Conut:4332899

線程狀態:

 

java線程入門一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.