经典多线程例子:售卖火车票 要求销售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(); } }测试结果:
如有问题欢迎指正