zoukankan      html  css  js  c++  java
  • java多线程售票窗口问题

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    //第一种加锁方式 lock 和 unlock
    class myThread implements Runnable{
        //售票总数
        private int tickets = 100;
        //定义锁
        private Lock lock = new ReentrantLock();
        
        public void run(){
            while(true){
                //加锁
                lock.lock();
                if(tickets>0){
                    try{
                        Thread.sleep(100);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+" "+(tickets--));
                }
                lock.unlock();
            }
        }
    }
    //第二种 synchronized
    class MyRunnable implements Runnable{
        private int tickets = 100;
        public void run(){
            while(true){
                synchronized(this){
                    if(tickets>0){
                        try{
                            Thread.sleep(100);
                        }catch(InterruptedException e){
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+" "+(tickets--));
                    }
                }
            }
        }
    }
    public class Test {
        public static void main(String[] args){
            MyRunnable thread = new MyRunnable();
            Thread t1 = new Thread(thread);
            Thread t2 = new Thread(thread);
            Thread t3 = new Thread(thread);
            t1.start();
            t2.start();
            t3.start();
        }
    }
  • 相关阅读:
    夜生活
    LOST
    TMD
    玩AJAX要先知道这些
    水漫金陵
    家装
    JAVA里面的小名堂
    朋友值多少钱
    猪八戒
    冬枣
  • 原文地址:https://www.cnblogs.com/wysAC666/p/9811278.html
Copyright © 2011-2022 走看看