JUC-7-lock Interface

Solve the multi-thread-safe manner
 
synchronized implicit lock   
1. The sync block 
2. The synchronization method
 
3. Lock explicit synchronization lock locks lock () method lock unlock () releases the lock
 
package com.wf.zhang.juc;

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

public class TestLock {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket,"1号窗口").start();
        new Thread(ticket,"2号窗口").start();
        new Thread(ticket,"3号窗口").start();
    }
}


class  Ticket implements Runnable{

    private  int tick = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){

            //上锁
            lock.lock();

            try {
                if (tick>0){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    System.out.println(Thread.currentThread().getName() +"完成售票,余票为 "+ --tick);
                }
            } The finally {
                 // release lock 
                lock.unlock (); 
            } 

        } 
    } 
}

 

Guess you like

Origin www.cnblogs.com/wf-zhang/p/12080320.html