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類方式: java

(1)優勢:編寫簡單,若是須要訪問當前線程,無需使用Thread.currentThread()方法,直接使用this,便可得到當前線程。 編程

(2)缺點:由於線程類已經繼承了Thread類,因此不能再繼承其餘的父類。 採用實現Runnable接口方式:ide

採用實現Runnable接口的方式: this

(1)優勢:線程類只是實現了Runable接口,還能夠繼承其餘的類。在這種方式下,能夠多個線程共享同一個目標對象,因此線程

很是適合多個相同線程來處理同一份資源的狀況,從而能夠將CPU代碼和數據分開,造成清晰的模型,較好地體現了面向對象對象

的思想。繼承

(2)缺點:編程稍微複雜,若是須要訪問當前線程,必須使用Thread.currentThread()方法。接口

相關文章
相關標籤/搜索