java线程同步--lock锁(JDK 5 新增)

需手动加锁和释放.

 

package com.LearnJava.Thread;

import java.util.concurrent.locks.ReentrantLock;

/*
    同步代码块
    synchronized(同步监视器){
        //需要同步的代码
    }
    同步监视器:俗称 锁,可以是任何实例化的类.但是需要共用同一个实例.
 */
class WindowSell implements Runnable{
    ReentrantLock lock = new ReentrantLock();
    private int ticket = 100;
    @Override
    public void run() {
        while (true) {
            try {

                lock.lock();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "sell " + ticket--);
                    Thread.sleep(100);

                }else{
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}
public class ThreadTestTicket {
    public static void main(String[] args) {
        WindowSell win = new WindowSell();
        Thread t1 = new Thread(win);
        t1.setName("1号窗口");
        Thread t2 = new Thread(win);
        t2.setName("2号窗口");
        Thread t3 = new Thread(win);
        t3.setName("3号窗口");

        t1.start();
        t2.start();
        t3.start();
    }
}

 

posted @ 2020-02-08 15:35  超级学渣渣  阅读(235)  评论(0编辑  收藏  举报