經典多線程例子:售賣火車票
要求銷售1000張票,要求有10個窗口來進行銷售, 請編寫多線程程序來模擬這個效果
public class MyTask implements Runnable{
private int ticket = 10;
@Override
public void run() {
while(true){
synchronized(this){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"正在售賣第"+ticket+"張票");
ticket--;
}else{
System.out.println(Thread.currentThread().getName()+"退出售票");
break;
}
}
}
}
}
public static void main(String[] args) {
MyTask task = new MyTask();
for(int i = 0;i<5;i++){
new Thread(task,"窗口"+(i+1)).start();
}
}
測試結果:
如有問題歡迎指正