解决共享资源冲突问题2

使用Lock类

package com.miller.datastructure.thread;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

/**

* @program: data-structure

* @description: 使用Lock对象

* @author: Miller.FAN

* @create: 2019-10-20 17:52

**/

public class UseLockimplements Runnable{

private Locklock =new ReentrantLock();// 使用显示的Lock对象解决共享资源竞争

    Doublea =2.12345;

Doubleb =3.12345;

@Override

    public void run() {

lock.lock();

try {

Double c =a+b;

System.out.println(Thread.currentThread() +"双精度浮点值:c = " + c);

}catch (Exception e) {

e.printStackTrace();

}finally {

lock.unlock();

}

}

public static void main(String[] args) {

Thread miller_thread =new Thread(new UseLock(),"miller_thread");

Thread bill_thread =new Thread(new UseLock(),"bill_thread");

miller_thread.start();

bill_thread.start();

}

}

显式的Lock对象在加锁和释放锁方面,相对于内建的synchronized锁来说,还赋予了你更细粒度的控制力。

你可能感兴趣的:(解决共享资源冲突问题2)