Java线程-实现售票

/**
 * 窗口卖票问题线程
 * 
 * @author wyh
 * 
 */
public class ThreadDemo {


/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
/**
* 开通A、B、C 3个窗口,同时卖票
*/
Ticket t = new Ticket();
Thread t1 = new Thread(t, "A");
Thread t2 = new Thread(t, "B");
Thread t3 = new Thread(t, "C");
t1.start();
t2.start();
t3.start();
}


}


class Ticket implements Runnable {
//可售票数量
private int ticketCount = 10;


@Override
public void run() {
while (true) {
synchronized (this) {//加锁避免重复卖票
if (ticketCount > 0) {//如果可售票大于0则继续销售,否则结束
System.out.println(Thread.currentThread().getName() + "销售第" + (ticketCount--)+"张");
} else {
break;
}
}


try {//当前窗口休息一会,让其他窗口卖票
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}
}

你可能感兴趣的:(java)