Java多线程经典案例(售票)

定义Sell类实现Runnable接口(很好的解决了单继承共享资源问题)

public class Sell implements Runnable {
	// 共100张票,三个售票窗口售卖
	private int tickets = 100;
	Object obj = new Object();	

	@Override		//重写run方法
	public void run() {
		while (true) {
			synchronized (obj) { // synchronized(对象) 线程同步机制,解决了重复抢占现象
				if (tickets > 0) {
					try {
						Thread.sleep(100); // sleep();休眠100毫秒
					} catch (InterruptedException e) {	//抛出异常

						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + "正在出售第: " + (tickets--) + " 张票");
				}
			}
		}
	}
}

/** 测试类 */
public class SellDemo {
	public static void main(String[] args) {
		Sell s = new Sell();
		//三个售票口
		Thread t1 = new Thread(s, "窗口1");
		Thread t2 = new Thread(s, "窗口2");
		Thread t3 = new Thread(s, "窗口3");
		//启动线程
		t1.start();
		t2.start();
		t3.start();
	}
}

你可能感兴趣的:(Java)