线程的死锁问题

2020-12-15  本文已影响0人  冯宏志
解决线程安全问题的方式三:Lock锁(JDK5新增)
  1. 实例化ReentrantLock(ReentrantLock是实现了Lock接口的一个类)
  2. 调用锁定方法fflock()
  3. 调用解锁unlock()
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        Window w = new Window();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

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

class Window implements Runnable{
    private int ticket = 100;
    //实例化ReentrantLock
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                //调用锁定lock()
                lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "买票,票号为:" + ticket);
                    ticket--;
                } else
                    break;
            } finally {
                //调用解锁方法unlock()
                lock.unlock();
            }
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读