使用AtomicInteger完成多线程售票
```java
package com.zhazha.juc;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author zhazha
* @version 1.0.0
* @date 2019/10/19 9:39
* @msg
**/
public class TestTicketAtomicLock {
@Test
public void test01() throws Exception {
CountDownLatch latch = new CountDownLatch(3);
TicketAtomic ticket = new TicketAtomic(latch);
for (int i = 0; i < 3; i++) {
new Thread(ticket).start();
}
latch.await();
}
@Test
public void test() throws Exception {
CountDownLatch latch = new CountDownLatch(3);
TicketNonAtomic ticket = new TicketNonAtomic(latch);
for (int i = 0; i < 3; i++) {
new Thread(ticket).start();
}
latch.await();
}
}
class TicketAtomic implements Runnable {
private AtomicInteger ticket = new AtomicInteger(100);
private CountDownLatch latch;
public TicketAtomic(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
while (true) {
try {
int temp = ticket.get();
if (temp > 0) {
// TimeUnit.MILLISECONDS.sleep(100);
if (ticket.compareAndSet(temp, ticket.get() - 1)) {
System.out.println(Thread.currentThread().getName() + " \t成功售票, 余票为: " + ticket.get());
}
}
else {
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
latch.countDown();
}
}
class TicketNonAtomic implements Runnable {
private Integer ticket = 100;
private Lock lock = new ReentrantLock();
private CountDownLatch latch;
public TicketNonAtomic(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
while (true) {
lock.lock();
try {
if (ticket > 0) {
// TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread().getName() + " \t成功售票, 余票为: " + --ticket);
}
else {
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
latch.countDown();
}
}