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();
    }
}

 

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务