java并发编程

学完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; //default
    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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值