天天看點

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

/**
 * 使用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代碼和資料分開,形成清晰的模型,較好地展現了面向對象

繼續閱讀