public class Demo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub //多线程并行时,会出现的问题 //同步: //买火车票,四个窗口A,B,C,D //创建任务 TicketTask task = new TicketTask(); //四个窗口A,B,C,D new Thread(task).start(); new Thread(task).start(); new Thread(task).start(); new Thread(task).start(); }}
//买票的任务
class TicketTask implements Runnable{//假设只有100张票
private static int ticket = 100; //同步方法 @Override public synchronized void run() { while(true){ if(ticket <= 0){ System.out.println("火车票已经卖完了....."); break; }else{ System.out.println("恭喜你买到火车票:座号:" + ticket); ticket--; } } }}