Java線程:線程的調度-優先順序

來源:互聯網
上載者:User

線程的優先順序用1-10之間的整數表示,數值越大優先順序越高,預設的優先順序為5。

在一個線程中開啟另外一個新線程,則新開線程稱為該線程的子線程,子線程初始優先順序與父線程相同。

/**
* Java線程:線程的調度-優先順序
*
* @author leizhimin
*/
public class Test {
         public static void main(String[] args) {
                 Thread t1 = new MyThread1();
                 Thread t2 = new Thread(new MyRunnable());
                 t1.setPriority(10);
                 t2.setPriority(1);
                 t2.start();
                 t1.start();
         }
}
class MyThread1 extends Thread {
         public void run() {
                 for (int i = 0; i < 10; i++) {
                         System.out.println("線程1第" + i + "次執行!");
                         try {
                                 Thread.sleep(100);
                         } catch (InterruptedException e) {
                                 e.printStackTrace();
                         }
                 }
         }
}
class MyRunnable implements Runnable {
         public void run() {
                 for (int i = 0; i < 10; i++) {
                         System.out.println("線程2第" + i + "次執行!");
                         try {
                                 Thread.sleep(100);
                         } catch (InterruptedException e) {
                                 e.printStackTrace();
                         }
                 }
         }
}

線程1第0次執行!
線程2第0次執行!
線程2第1次執行!
線程1第1次執行!
線程2第2次執行!
線程1第2次執行!
線程1第3次執行!
線程2第3次執行!
線程2第4次執行!
線程1第4次執行!
線程1第5次執行!
線程2第5次執行!
線程1第6次執行!
線程2第6次執行!
線程1第7次執行!
線程2第7次執行!
線程1第8次執行!
線程2第8次執行!
線程1第9次執行!
線程2第9次執行!
Process finished with exit code 0

出處:http://lavasoft.blog.51cto.com/62575/221801

聯繫我們

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