多线程-lock锁-模拟火车票购票-模拟生产线

使用Lock和Condition接口的await(),signal(),signalAll():
private final Lock lock = new ReentrantLock();创建锁
private Condition = Lock . newCondition();创建接口
lock.lock;上锁
lock.unlock;释放锁

模拟12306;假设100张票;五个线程抢票;不可以有两个或两个以上的线程订到同一张票;

当最后一张票买完之后,再订火车票就抛出异常提示:票已卖完;买票方法saleTicket;

 

/**
 * 模拟12306,假设100张票,用五个线程抢票,不可以有两个或两个以上的线程订到同一张票;
 * 当最后一张票买完之后,再订火车票就抛出异常提示:票已卖完;买票方法saleTicket;
 */
public class Ticket implements Runnable{
    /**
     * 只有100张票
     */
    private int num =100;
    @Override
    public void run () {
        for (int i = 0; i <30 ; i++) {
            try {
                saleTicket();
            }catch (Exception e){
                System.out.println("票已售完");
            }

        }

    }
    public synchronized  void saleTicket(){
        if(num>0){
            System.out.println(Thread.currentThread().getName()+"购买了第"+num--);
        }else {
            throw new RuntimeException(Thread.currentThread().getName()+"票已售完");
        }
    }
}


public class Test {
    public static void main ( String[] args ) {
        Ticket ticket =new Ticket();
        new Thread(ticket,"zhangsan").start();
        new Thread(ticket,"lisi").start();
        new Thread(ticket,"wangwu").start();
        new Thread(ticket,"zhaoliu").start();
    }
}

 

使用多线程实现流程化组装产品操作,每个生产线生产一个字(完整产品)
生产线A生产:完;
生产线B生产:整;
生产线C生产:产;
生产线D生产:品;
生产线E作为消费者(打印出:完整产品)

/**
 * 使用多线程实现流程化组装产品操作(完整产品)
 * 生产线A生产:完
 * 生产线B生产:整
 * 生产线C生产:产
 * 生产线D生产:品
 * E:消费:完整产品
 */
public class ShareResource {
    private String name = "";
    /**
     * 0--A;1--B;2--C;3--D; 4--E
     */
    private int product = 0;
    private final Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();
    private Condition conditionD = lock.newCondition();
    private Condition conditionE = lock.newCondition();

    //生产者对象
    public void pushLock ( String name ) {
        try {//获取锁
            lock.lock();
            //获取当前线程名称
            String threadName = Thread.currentThread().getName();
            if ("A".equals(threadName) && product != 0) {
                //以上条件成立,A进入等待状态
                conditionA.await();
            } else if ("B".equals(threadName) && product != 1) {
                //以上条件成立B进入等待状态
                conditionB.await();
            } else if ("C".equals(threadName) && product != 2) {
                //以上条件成立C进入等待状态
                conditionC.await();
            } else if ("D".equals(threadName) && product != 3) {
                //以上条件成立D进入等待状态
                conditionD.await();
            }
            //对产品进行拼接
            this.name = this.name + name;

            //对应生产结束后需要自加1
            this.product++;

            System.out.println("当前线程:"+threadName+",正在生产:"+name);
            //唤醒其他生产线程
            if ("A".equals(threadName)) {
                //A生产结束后B进入生产
                conditionB.signal();
            } else if ("B".equals(threadName)) {
                //B生产结束后C进入生产
                conditionC.signal();
            } else if ("C".equals(threadName)) {
                //C生产结束后D进入生产
                conditionD.signal();
            } else if ("D".equals(threadName)) {
                //以上条件成立D进入等待状态
                conditionE.signal();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    //消费者对象
    public void popLock () {
        try {
            lock.lock();
            //资源为空时需要等待,休眠,进行if判断,消费者消费
            if(product!=4){
                conditionE.await();
            }
            System.out.println("产品:" + this.name);

            //要将数据归零再次生产
            this.product = 0;

            //打印数据从新开始
            this.name = "";

            //消费结束后再次进入循环,只需要唤醒A线程
            conditionA.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }
}


public class ProductA implements Runnable {
    private ShareResource resource = null;
    public ProductA(ShareResource resource){
        this.resource = resource;

    }
    @Override
    public void run () {
        for (int i = 0; i <30 ; i++) {
            resource.pushLock("");
        }

    }
}

public class ProductB implements Runnable {
    private ShareResource resource = null;
    public ProductB(ShareResource resource){
        this.resource = resource;
    }
    @Override
    public void run () {
        for (int i = 0; i <30; i++) {
            resource.pushLock("");
        }

    }
}
public class ProductC implements Runnable {
    private ShareResource resource = null;
    public ProductC(ShareResource resource){
        this.resource = resource;
    }
    @Override
    public void run () {
        for (int i = 0; i <30; i++) {
            resource.pushLock("产");
        }

    }
}
public class ProductD implements Runnable {
    private ShareResource resource = null;
    public ProductD(ShareResource resource){
        this.resource = resource;
    }
    @Override
    public void run () {
        for (int i = 0; i <30; i++) {
            resource.pushLock("品");
        }

    }
}
public class ProductE implements Runnable{
    private ShareResource resource = null;
    public ProductE(ShareResource shareResource){
        this.resource=shareResource;
    }
    @Override
    public void run () {
        for (int i = 0; i <30 ; i++) {
            resource.popLock();
        }
    }
}
public class Test {
    public static void main ( String[] args ) {
        ShareResource shareResource = new ShareResource();
        //ProductA productA = new ProductA(shareResource);
        //new Thread(productA,"A").start();
        new Thread(new ProductA(shareResource) , "A").start();
        new Thread(new ProductB(shareResource) , "B").start();
        new Thread(new ProductC(shareResource) , "C").start();
        new Thread(new ProductD(shareResource) , "D").start();
        new Thread(new ProductE(shareResource)).start();

    }
}

 

posted @ 2022-05-04 23:18  280887072  阅读(152)  评论(0编辑  收藏  举报