package com.qiansi.szy.mqtt;
import java.util.concurrent.locks.ReentrantLock;
public class Test1 implements Runnable {
private int tickets = 100;
ReentrantLock lock=new ReentrantLock(false);
@Override
public void run() {
//只能一个卖:synchronized
// synchronized (this) {
// while (tickets > 0) {
// if (tickets > 0) {
// System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
// tickets--;
// }
// }
// }
//只能一个卖:lock方法
// lock.lock();
// try {
// while (tickets > 0) {
// if (tickets > 0) {
// System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
// tickets--;
// }
// }
// } catch (Exception e) {
//
// } finally {
// lock.unlock();
// }
//只保证票数正确,大家都可以卖:synchronized
while (tickets > 0) {
synchronized (this) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
tickets--;
}
}
}
//只保证票数正确,大家都可以卖: lock方法
// while (tickets > 0) {
// lock.lock();
// try {
// if (tickets > 0) {
// System.out.println(Thread.currentThread().getName() + "卖了第" + (100 - tickets + 1) + "张票");
// tickets--;
// }
// } catch (Exception e) {
//
// } finally {
// lock.unlock();
// }
// }
}
public static void main(String[] args) {
Test1 tt = new Test1();
Thread th1 = new Thread(tt, "1号窗口");
Thread th2 = new Thread(tt, "2号窗口");
th1.start();
th2.start();
}
}