Skip to content

Instantly share code, notes, and snippets.

@kentkwan
Created May 15, 2013 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentkwan/5583617 to your computer and use it in GitHub Desktop.
Save kentkwan/5583617 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) {
List<Ticket> sellingTickets = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
sellingTickets.add(new Ticket(i));
}
for (int i = 0; i < 1000; ++i) {
new Thread(new Consumer(i, sellingTickets)).start();
}
}
}
class Ticket {
private Integer id;
private Lock lock = new ReentrantLock();
private boolean sold = false;
public Ticket(Integer id) {
this.id = id;
}
public void sold(Consumer consumer) {
try {
lock.lock();
if (sold)
return;
sold = true;
System.out.println(consumer.getId() + "号顾客抢到了" + id + "号票");
} finally {
lock.unlock();
}
}
}
class Consumer implements Runnable {
private Integer id;
private List<Ticket> sellingTickets;
public Consumer(Integer id, List<Ticket> sellingTickets) {
this.id = id;
this.sellingTickets = sellingTickets;
}
@Override
public void run() {
for (Ticket ticket : sellingTickets) {
ticket.sold(this);
}
}
public Integer getId() {
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment