java實現多線程的兩種方式

來源:互聯網
上載者:User

標籤:dem   ticket   inter   直接   控制   ext   並發   bsp   run   

Java需要並發控制三個原因:

  1. 多線程環境
  2. 存在共用資源
  3. 多個線程操作(修改)共用資源

下面分別用繼承Thread類和實現Runnable介面倆種方式實現並發控制,

繼承Thread類

繼承Thread類方式,最後建立對象是因為會是三個不同的線程對象,所以需要將共用資源和鎖都靜態化,如果不這樣的話,就不存在共用資源一說了,自然也沒有並發控制的說法。

class MyThread extends Thread{    //電影票總數100張    private static int ticket=100;    //鎖對象    private static Object obj = new Object();    @Override    public void run() {        while(true){            synchronized (obj) {                            if(ticket>0){                System.out.println(this.currentThread().getName()+"正在出售第"+ticket--+"張票");            }            }            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}public class ThreadDemo {    public static void main(String[] args) {        Thread t1 = new MyThread();        Thread t2 = new MyThread();        Thread t3 = new MyThread();        t1.setName("售票員1");        t2.setName("售票員2");        t3.setName("售票員3");        t1.start();        t2.start();        t3.start();    }}
實現Runnable介面

實現Runnable介面方式,因為建構函式中,需要傳入一個Runnable介面類型,所以這裡就直接存在共用資源了,靜態修飾可有可無,但是還是寫上比較好。

class MyRunnable implements Runnable{    //電影票總數100張    private int ticket=100;    //鎖對象    private Object obj = new Object();    @Override    public void run() {        while(true){            synchronized (obj) {                            if(ticket>0){                System.out.println(Thread.currentThread().getName()+"正在出售第"+ticket--+"張票");            }            }            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}public class RunnableDemo {    public static void main(String[] args) {        Runnable r = new MyRunnable();        Thread t1 = new Thread(r,"售票員1");        Thread t2 = new Thread(r,"售票員2");        Thread t3 = new Thread(r,"售票員3");        t1.start();        t2.start();        t3.start();    }}

 

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.