標籤:ticket print over int 資料 對象 his 處理 賣出
/** * 使用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中實現多線程的兩種方式