Java的lock

1.案例1

1)调用类(lock)

package shapes;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
    private int tickets = 100;
    private Lock lock = new ReentrantLock();
    
    @Override
    public void run() {
        while(true) {
            lock.lock();
            if(tickets > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票。");
                //买票
                tickets --;
            }
            lock.unlock();
        }
    }
}

 

 

2.调用类2(synchronized)

package shapes;

public class SellTicket implements Runnable {
    private static int tickets = 100;
    private Object obj = new Object();
    @Override
    public void run() {
        while(true) {
            sellTicket();
        }
    }
    
    private static synchronized void sellTicket() {
        if(tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票。");
            //买票
            tickets --;
        }    }
}

 

3.使用方式

package shapes;

public class Main {

    public static void main(String[] args) {
        SellTicket st = new SellTicket();
        Thread t1 = new Thread(st,"窗口1");
        Thread t2 = new Thread(st,"窗口2");
        Thread t3 = new Thread(st,"窗口3");
        
        t1.start();
        t2.start();
        t3.start();
        
    }

}

4.结果

 

 

参阅:https://www.bilibili.com/video/BV1vk4y117fU?p=338

 

posted @ 2022-03-31 15:10  蜗牛的礼物  阅读(30)  评论(0编辑  收藏  举报