如何使用多線程處理賣火車票
public class Windows implements Runnable{
int ticket=100;
Object obj=new Object();
public void run() {
while(true) {
synchronized (obj) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ticket>0) {
System.out.println(Thread.currentThread().getName()+"售票,票号為"+ticket--+"---------還剩"+ticket+"張票");
}else {
break;
}
}
}
}
}
測試類
ublic static void main(String[] args) {
//
Runnable runnable=new Windows();
Thread t1=new Thread(runnable);
Thread t2=new Thread(runnable);
Thread t3=new Thread(runnable);
t1.setName("視窗1");
t2.setName("視窗2");
t3.setName("視窗3");
t1.start();
t2.start();
t3.start();
}
}