Created
May 15, 2013 12:21
-
-
Save kentkwan/5583617 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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