Java中實現多線程的兩種方式

來源:互聯網
上載者:User

標籤:ticket   print   over   int   資料   對象   his   處理   賣出   

/** * 使用Thread類類比4個售票視窗共同賣100張火車票的程式 *  * 沒有共用資料,每個線程各賣100張火車票 *  * @author jiqinlin * */public class ThreadTest {    public static void main(String[] args){        new MyThread().start();        new MyThread().start();        new MyThread().start();        new MyThread().start();    }        public static class MyThread extends Thread{        //車票數量        private int tickets=100;        @Override        public void run() {            while(tickets>0){                System.out.println(this.getName()+"賣出第【"+tickets--+"】張火車票");            }        }    }}


/** * 使用Runnable介面類比4個售票視窗共同賣100張火車票的程式 *  * 共用資料,4個線程共同賣這100張火車票 * @author jiqinlin * */public class RunnableTest {    public static void main(String[] args) {        Runnable runnable=new MyThread();        new Thread(runnable).start();        new Thread(runnable).start();        new Thread(runnable).start();        new Thread(runnable).start();    }        public static class MyThread implements Runnable{        //車票數量        private int tickets=100;        public void run() {            while(tickets>0){                System.out.println(Thread.currentThread().getName()+"賣出第【"+tickets--+"】張火車票");            }        }            }}


採用繼承Thread類方式: 

(1)優點:編寫簡單,如果需要訪問當前線程,無需使用Thread.currentThread()方法,直接使用this,即可獲得當前線程。 

(2)缺點:因為線程類已經繼承了Thread類,所以不能再繼承其他的父類。 採用實現Runnable介面方式:

採用實現Runnable介面的方式: 

(1)優點:線程類只是實現了Runable介面,還可以繼承其他的類。在這種方式下,可以多個線程共用同一個目標對象,所以

非常適合多個相同線程來處理同一份資源的情況,從而可以將CPU代碼和資料分開,形成清晰的模型,較好地體現了物件導向

的思想。

(2)缺點:編程稍微複雜,如果需要訪問當前線程,必須使用Thread.currentThread()方法。


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.