Java繼承thread類與實現Runnable接口

Java中線程的創建有兩種方式:

1.  通過繼承Thread類,重寫Thread的run()方法,將線程運行的邏輯放在其中

2.  通過實現Runnable接口,實例化Thread類


Java 購票實例:

class MyThread extends Thread{  
      
    private int ticket = 10;  
    private String name;  
    public MyThread(String name){  
        this.name =name;  
    }  
      
    public void run(){  
        for(int i =0;i<500;i++){  
            if(this.ticket>0){  
                System.out.println(this.name+"賣票---->"+(this.ticket--));  
            }  
        }  
    }  
}  
public class ThreadDemo {  
    public static void main(String[] args) {  
        MyThread mt1= new MyThread("一號窗口");  
        MyThread mt2= new MyThread("二號窗口");  
        MyThread mt3= new MyThread("三號窗口");  
        mt1.start();  
        mt2.start();  
        mt3.start();  
    }  
  
}  
運行結果如下:

一號窗口賣票---->10  
一號窗口賣票---->9  
二號窗口賣票---->10  
一號窗口賣票---->8  
一號窗口賣票---->7  
一號窗口賣票---->6  
三號窗口賣票---->10  
一號窗口賣票---->5  
一號窗口賣票---->4  
一號窗口賣票---->3  
一號窗口賣票---->2  
一號窗口賣票---->1  
二號窗口賣票---->9  
二號窗口賣票---->8  
三號窗口賣票---->9  
三號窗口賣票---->8  
三號窗口賣票---->7  
三號窗口賣票---->6  
三號窗口賣票---->5  
三號窗口賣票---->4  
三號窗口賣票---->3  
三號窗口賣票---->2  
三號窗口賣票---->1  
二號窗口賣票---->7  
二號窗口賣票---->6  
二號窗口賣票---->5  
二號窗口賣票---->4  
二號窗口賣票---->3  
二號窗口賣票---->2  
二號窗口賣票---->1

class MyThread1 implements Runnable{  
    private int ticket =10;  
    private String name;  
    public void run(){  
        for(int i =0;i<500;i++){  
            if(this.ticket>0){  
                System.out.println(Thread.currentThread().getName()+"賣票---->"+(this.ticket--));  
            }  
        }  
    }  
}  
public class RunnableDemo {  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        //設計三個線程  
         MyThread1 mt = new MyThread1();  
         Thread t1 = new Thread(mt,"一號窗口");  
         Thread t2 = new Thread(mt,"二號窗口");  
         Thread t3 = new Thread(mt,"三號窗口");  
//         MyThread1 mt2 = new MyThread1();  
//         MyThread1 mt3 = new MyThread1();  
         t1.start();  
         t2.start();  
         t3.start();  
    }  
}  

一號窗口賣票---->10  
三號窗口賣票---->9  
三號窗口賣票---->7  
三號窗口賣票---->5  
三號窗口賣票---->4  
三號窗口賣票---->3  
三號窗口賣票---->2  
三號窗口賣票---->1  
一號窗口賣票---->8  
二號窗口賣票---->6 

在我們剛接觸的時候可能會迷糊繼承Thread類和實現Runnable接口實現多線程,其實在接觸後我們會發現這完全是兩個不同的實現多線程,一個是多個線程分別完成自己的任務,一個是多個線程共同完成一個任務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章