Java創建線程的第二種方式:實現runable接口




/*
需求:簡單的賣票程序
多個窗口買票

創建線程的第二種方式:實現runable接口


*/
/*步驟
1.定義類實現Runable接口
2.覆蓋Runable接口中的run方法
    將線程要運行的代碼存放在該run方法中

3.通過Thread類建立線程對象
4.將Runable接口的子類對象作為實際參數傳遞給Thread類的構造函數
  為什么要將Runable接口的子類對象傳遞給Thread的構造函數。
  因為,自定義的run方法所屬的對象是Runable接口的子類對象
  所以要讓線程去指定對象的Run方法,就必須明確該run方法所屬對象

5.調用Thread類的start方法開啟線程並調用Runable接口子類的Run方法

實現方式和繼承方式有什么區別?(面試題經常考)
實現方式好處:避免了單繼承的局限性
在定義線程時,建議使用實現方式

兩種方式區別:
繼承Thread:線程代碼存放Thread子類的run方法中
實現Runable:線程代碼存在接口的子類的run方法  

*/

class Ticket implements Runnable //extends Thread
{
    private static int tick=100;
    public void run()
    {
        while(true)
        {
            if(tick>0)
            {
                System.out.println(Thread.currentThread().getName()+"sale:--"+tick--);
            }
        }
    }
}

class TicketDemo
{
    public static void main(String args[])
    {
        Ticket t=new Ticket();
        Thread t1=new Thread(t);
        Thread t2=new Thread(t);
        Thread t3=new Thread(t);
        Thread t4=new Thread(t);
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM