Java多线程(三):Synchronized与Lock的使用

Java 2020-04-25 659 次浏览 本文字数:5473字

本文主要内容:Lock锁解决卖票问题、Lock版的生产者与消费者和Synchronized与Lock区别

Lock锁解决卖票问题

1.Synchronized版

public class SaleTicket_Synchronized {
    public static void main(String[] args) {
        Ticket_Synchronized ticket_synchronized = new Ticket_Synchronized();

        new Thread(() -> { for (int i = 0; i <= 100; i++) ticket_synchronized.sale(); }, "A").start();
        new Thread(() -> { for (int i = 0; i <= 100; i++) ticket_synchronized.sale(); }, "B").start();
        new Thread(() -> { for (int i = 0; i <= 100; i++) ticket_synchronized.sale(); }, "C").start();
    }
}

// 资源类,通过多线程操作同一个资源类
class Ticket_Synchronized{
    private int ticket = 100;

    public synchronized void sale(){
        if (ticket > 0){
            System.out.println(Thread.currentThread().getName() + "卖出出了第" + ticket-- + "张票,剩余" + ticket + "张");
        }
    }
}

2.Lock版

public class SaleTicket_Lock {
    public static void main(String[] args) {
        Ticket_Lock ticket_lock = new Ticket_Lock();

        new Thread(() -> { for (int i = 0; i <= 100; i++) ticket_lock.sale(); }, "A").start();
        new Thread(() -> { for (int i = 0; i <= 100; i++) ticket_lock.sale(); }, "B").start();
        new Thread(() -> { for (int i = 0; i <= 100; i++) ticket_lock.sale(); }, "C").start();
    }
}

// 资源类,通过多线程操作同一个资源类
class Ticket_Lock{
    private int ticket = 100;
    Lock lock = new ReentrantLock();

    public void sale(){
        // 加锁
        lock.lock();
        try {
            if (ticket > 0){
                System.out.println(Thread.currentThread().getName() + "卖出出了第" + ticket-- + "张票,剩余" + ticket + "张");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}

Lock版的生产者与消费者(线程间的通信问题)

1.此案例为:交替打印10次数字+1与数字-1

2.Synchronized版

public class ProducerAndConsumer_Synchronized {
    public static void main(String[] args) {
        Data_Synchronized data_synchronized = new Data_Synchronized();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data_synchronized.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data_synchronized.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

class Data_Synchronized{
    private int data = 0;

    // data + 1 方法
    public synchronized void increment() throws InterruptedException {
        while (data != 0) {
            //等待
            this.wait();
        }
        //执行
        data += 1;
        System.out.println(Thread.currentThread().getName() + "-->" + data);
        //通知其它线程我已经完成+1
        this.notifyAll();
    }

    // data - 1 方法
    public synchronized void decrement() throws InterruptedException {
        while (data == 0) {
            //等待
            this.wait();
        }
        //执行
        data -= 1;
        System.out.println(Thread.currentThread().getName() + "-->" + data);
        //通知其它线程我已经完成-1
        this.notifyAll();
    }
}

3.Lock版

public class ProducerAndConsumer_Lock {
    public static void main(String[] args) {
        Data_Lock data_lock = new Data_Lock();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data_lock.increment();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data_lock.decrement();
            }
        }, "B").start();

    }
}

class Data_Lock{
    private int data = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    // data + 1 方法
    public void increment(){
        lock.lock();
        try {
            while (data != 0) {
                //等待
                condition.await();
            }
            //执行
            data += 1;
            System.out.println(Thread.currentThread().getName() + "-->" + data);
            //通知其它线程我已经完成+1
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // data - 1 方法
    public void decrement(){
        lock.lock();
        try {
            while (data == 0) {
                //等待
                condition.await();
            }
            //执行
            data -= 1;
            System.out.println(Thread.currentThread().getName() + "-->" + data);
            //通知其它线程我已经完成+1
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

Synchronized与Lock区别

1、Synchronized是Java关键字,Lock是一个Java类
2、Synchronized无法判断锁的状态,Lock可以判断是否获取到了锁
3、Synchronized会自动释放锁,Lock必须要手动释放(否则造成死锁问题)
4、Synchronized中线程1如果获得锁并阻塞,线程2会一直等待,Lock锁就不一定会等待下去
5、Synchronized是可重入锁,不可以中断,非公平,Lock是可重入锁,不可以中断,非公平(但可以使用new ReentrantLock(true)的方式改变公平)
6、Synchronized适合少量代码同步问题,Lock锁适合大量的同步代码


本文由 WarlockMT 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。