学完think in java并发编程部分,写了个程序,熟悉一下
import java.util.concurrent.locks.*;
import java.util.concurrent.*;
class Ticket{
public static int number = 0;
public final int id = ++number;
}
abstract class Cinema{
public int SIZE = 1000;
public Ticket[] tickets;
public int index = 0;
public Cinema(){}
public Cinema(int SIZE) {
this.SIZE = SIZE;
initTickets();
}
private void initTickets() {
tickets = new Ticket[SIZE];
for(int i = 0; i < SIZE; i++)
tickets[i] = new Ticket();
}
public abstract int sellTicket();
}
class SynchCinema extends Cinema{
private String identify;
public SynchCinema(String identify, int SIZE) {
super(SIZE);
this.identify = identify;
}
public int sellTicket() {
synchronized(this){
if(index < SIZE) {
System.out.println(identify + " sell " + tickets[index++].id + " ticket");
return 0;
} else {
System.out.println("Sell Out");
return -1;
}
}
}
}
class LockCinema extends Cinema{
private String identify;
private ReentrantLock lock = new ReentrantLock();
public LockCinema(String identify, int SIZE) {
super(SIZE);
this.identify = identify;
}
public int sellTicket() {
lock.lock();
if(index < SIZE) {
System.out.println(identify + " sell " + (tickets[index++].id - 10000) + " ticket");
} else {
System.out.println("Sell Out");
lock.unlock();
return -1;
}
lock.unlock();
return 0;
}
}
class TicketSeller implements Runnable{
private Cinema cinema;
public TicketSeller(Cinema cinema) {
this.cinema = cinema;
}
public void run() {
while(!Thread.interrupted()) {
int number = cinema.sellTicket();
if(number == -1) break;
}
}
}
public class SaleTicketsDemo{
public static void main(String args[]) {
ExecutorService exec = Executors.newCachedThreadPool();
SynchCinema synchCinema = new SynchCinema("Synch", 10000);
LockCinema lockCinema = new LockCinema("Lock", 10000);
exec.execute(new TicketSeller(synchCinema));
exec.execute(new TicketSeller(lockCinema));
try{
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
exec.shutdownNow();
}
}