Thread three multi-threaded ticketing service uses Lock lock

Lock

There is a thread safety problem in the ticket selling case (selling non-existent tickets and duplicate tickets). The
third solution is to use Lock to implement
java.util.concurrent.locks
Lock to provide more than the use of synchronized methods and statements. Extensive lock operation.
They allow for more flexible structuring, may have completely different properties, and can support multiple associated object Conditions.
Methods in the Lock interface:

  • void lock() acquire lock
  • Void unlock () release the lock

Steps to use java.util.concurrent.locks.ReentrantLock implements lock interface
:

  • 1. Create a Reentrantlock object at the member location
  • 2. Call the method Lock in the Lock interface to obtain the lock before the code that may have security problems
  • 3. After the code that may have security problems, call the method Unlock in the Lock interface to release the lock

Ticket sales code

public class RunnableImpl implements Runnable {
private int ticket=100;
//在成员位置创建一个Reentrantlock对象
Lock l= new ReentrantLock();

@Override
public void run() {
    while (true)
    {
        l.lock();
        if(ticket>0)
        {
            try {
                Thread.sleep(10);
                System.out.println(Thread.currentThread().getName()+"正在卖第"+ticket+"张票!");
                ticket--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                //在可能会出现安全问题的代码后面调用Lock接口中的方法Unlock释放锁
                l.unlock();//无论程序是否异常,都会把锁释放!
            }

        }

    }

}
}

Test code:

public class Demo01Ticket {
public static void main(String[] args) {
    RunnableImpl run=new RunnableImpl();
    Thread t0=new Thread(run);
    Thread t1=new Thread(run);
    Thread t2=new Thread(run);
    //调用start,开启多线程
    t0.start();
    t1.start();
    t2.start();
}
}

Realization effect:

Thread-0 is selling its 100th ticket!
Thread-0 is selling the 99th ticket!
Thread-0 is selling its 98th ticket!
Thread-0 is selling its 97th ticket!
Thread-0 is selling its 96th ticket!
Thread-0 is selling its 95th ticket!
Thread-0 is selling its 94th ticket!

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/102631352