Java 多線程Thread和Runnable

來源:互聯網
上載者:User

標籤:eve   system   ted   bsp   run   sleep   event   div   getname   

Thread:

class MyThread extends Thread{    private int ticketsCont=5; //一共有5張火車票    private String name; //視窗, 也即是線程的名字    public MyThread(String name){        this.name=name;    }    @Override    public void run(){        while(ticketsCont>0){            ticketsCont--; //如果還有票,就賣掉一張票            System.out.println(name+"賣掉了1張票,剩餘票數為:"+ticketsCont);        }    }}public class TicketsThread{    public static void main(String args[]){        //建立三個線程,類比三個視窗賣票        MyThread mt1=new MyThread("視窗1");        MyThread mt2=new MyThread("視窗2");        MyThread mt3=new MyThread("視窗3");        //啟動三個線程,也即是視窗,開始賣票        mt1.start();        mt2.start();        mt3.start();    }}
視窗1賣掉了1張票,剩餘票數為:4視窗1賣掉了1張票,剩餘票數為:3視窗1賣掉了1張票,剩餘票數為:2視窗1賣掉了1張票,剩餘票數為:1視窗1賣掉了1張票,剩餘票數為:0視窗3賣掉了1張票,剩餘票數為:4視窗2賣掉了1張票,剩餘票數為:4視窗3賣掉了1張票,剩餘票數為:3視窗3賣掉了1張票,剩餘票數為:2視窗3賣掉了1張票,剩餘票數為:1視窗3賣掉了1張票,剩餘票數為:0視窗2賣掉了1張票,剩餘票數為:3視窗2賣掉了1張票,剩餘票數為:2視窗2賣掉了1張票,剩餘票數為:1視窗2賣掉了1張票,剩餘票數為:0
View Code

Runnable介面:

class MyThread2 implements Runnable{    private int ticketsCont=5; //一共有5張火車票    @Override    public void run(){        while(true){            synchronized(this){                if(ticketsCont<=0){                    break;                }                ticketsCont--; //如果還有票,就賣掉一張票                System.out.println(Thread.currentThread().getName()+"賣掉了1張票,剩餘票數為:"+ticketsCont);                    /*try{                        Thread.sleep(50);  //通過阻塞程式來查看效果                    }                    catch(Exception e){                        System.out.println(e);                    }*/            }        }    }}public class TicketsRunnable{    public static void main(String args[]){        MyThread2 mt=new MyThread2();        //建立三個線程來類比三個售票視窗        Thread th1=new Thread(mt,"視窗1");        Thread th2=new Thread(mt,"視窗2");        Thread th3=new Thread(mt,"視窗3");        //啟動三個線程,也即是三個視窗,開始賣票        th1.start();        th2.start();        th3.start();    }}
視窗1賣掉了1張票,剩餘票數為:4視窗1賣掉了1張票,剩餘票數為:3視窗1賣掉了1張票,剩餘票數為:2視窗1賣掉了1張票,剩餘票數為:1視窗1賣掉了1張票,剩餘票數為:0
View Code

Thread類是多個線程分別完成自己的任務,Runnable是多個線程共同完成一個任務。

建議使用Runnable這種方式建立線程。 程式中的同一資源指的是同一個Runnable對象。安全的賣票程式中需要加入同步synchronized。

 

http://www.cnblogs.com/Li-Cheng/p/4332179.html

Java 多線程Thread和Runnable

聯繫我們

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