lock解决线程安全问题,与synchronize区别,同步的三种方式

发布时间 2023-08-23 23:55:21作者: sgj191024
package com.atjava.test;

import java.util.concurrent.locks.ReentrantLock;

class Window1 implements Runnable{

    private int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if(ticket > 0){
                    System.out.println(Thread.currentThread().getName() + "售票,票号为:" + ticket);
                    ticket--;
                }else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

public class LockTest {
    public static void main(String[] args) {
        Window1 windowRun = new Window1();
        Thread thread1 = new Thread(windowRun);
        Thread thread2 = new Thread(windowRun);
        Thread thread3 = new Thread(windowRun);
        thread1.setName("窗口一");
        thread2.setName("窗口二");
        thread3.setName("窗口三");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

  synchronize执行完同步代码就自动释放锁了,而lock需要手动的释放锁

 

 

同步的三种方式:同步方法,同步代码块,lock