在java平台多線程編程的程式員都知道,線程編程有2種實現辦法繼承Thread 和實現Runnable介面。
我們先來看用繼承的辦法實現。
public class MutliThread extends Thread{
private int ticket=100;//每個線程都擁有100張票
public void run(){
while(ticket>0){
System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
測試類別
public class MutliThreadDemo {
public static void main(String [] args){
MutliThread m1=new MutliThread("Window 1");
MutliThread m2=new MutliThread("Window 2");
MutliThread m3=new MutliThread("Window 3");
m1.start();
m2.start();
m3.start();
}
}