Java中實現多線程的兩種方式
阿新 • • 發佈:2018-02-06
窗口 -- his 面向對象 new thread 資源 pub string /**
* 使用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代碼和數據分開,形成清晰的模型,較好地體現了面向對象
的思想。
(2)缺點:編程稍微復雜,如果需要訪問當前線程,必須使用Thread.currentThread()方法。
Java中實現多線程的兩種方式