Java多线程之ReentrantLock使用-yellowcong

来源:互联网 发布:用java编写水仙花数 编辑:程序博客网 时间:2024/06/05 04:34

ReentrantLock是synchronized的替代,但是实现机制更加的复杂,以更加精确的对锁控制。ReentrantLock 的构造函数中

    public ReentrantLock() { // 默认是fair = false,非公平锁,等待时间越久越先进入        sync = new NonfairSync();    }    public ReentrantLock(boolean fair) {//设置是否是公平锁        sync = fair ? new FairSync() : new NonfairSync();    }

案例

两个线程中,通过Condition, 进行线程间的通信,通过ReentrantLock 可以更加精确的控制锁,这个例子是中,我开始只是锁了一部分,后来发现这种做法不对,需要将同步的代码块锁住,而不是只锁list集合

package yellowcong.day10_06;import java.util.LinkedList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;/** * 创建日期:2017年10月6日 <br/> * 创建用户:yellowcong <br/> * 功能描述:   */public class RentLocakDemo {    public static void main(String[] args) {        //独占锁,        //构造参数:公平和不公平的区别        //公平,等待时间越久,越优先调用        //不公平,释放锁后,各自竞争        final ReentrantLock lock = new ReentrantLock();        //获取Condition        final Condition  con = lock.newCondition();        final Condition  con2 = lock.newCondition();//      ConcurrentLinkedQueue<String>  // 如果用这个集合,那就完全不需要啥锁了        //定义一个集合,多个线程操作一个集合        final LinkedList<String> list =new LinkedList<String>();        Runnable run = new Runnable() {            public void run() {                while(true){                        try {                            lock.lock();                            if(list.size() >5){                                //等待                                con2.await();                            }else{                                list.add("xx数据");                                System.out.println(Thread.currentThread().getName()+"添加数据");                                Thread.sleep(500);                                con.signalAll();                            }                        } catch (InterruptedException e) {                            e.printStackTrace();                        }finally{                            lock.unlock();                        }                }            }        };        Runnable run2 = new Runnable() {            public void run() {                while(true){                        try {                            lock.lock();                            if(list.size() <=0){                                con.await();                            }else{                                String str = list.removeFirst();                                System.out.println(Thread.currentThread().getName()+"获取数据"+str);                                Thread.sleep(500);                                //通过ReentrantLock 可以更加精确的进行解锁操作                                if(list.size() <5){                                    //告诉 线程2 添加数据                                    con2.signalAll();                                }                            }                        } catch (InterruptedException e) {                            e.printStackTrace();                        }finally{                            lock.unlock();                        }                }            }        };        //定义一个缓存线程池,启动线程        ExecutorService executor = Executors.newCachedThreadPool();        executor.execute(run);        executor.execute(run);        executor.execute(run2);        executor.execute(run2);        executor.execute(run2);    }}

基于synchronized实现

package yellowcong.day10_06;import java.util.LinkedList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;/** * 创建日期:2017年10月6日 <br/> * 创建用户:yellowcong <br/> * 功能描述:   */public class RentLocakDefualtDemo {    public static void main(String[] args) {        //定义一个集合,多个线程操作一个集合        final LinkedList<String> list =new LinkedList<String>();        final Object lock = new Object();        Runnable run = new Runnable() {            public void run() {                while(true){                        synchronized (lock) {                            try {                                if(list.size() >5){                                    //等待                                    lock.wait();                                }else{                                    list.add("xx数据");                                    System.out.println(Thread.currentThread().getName()+"添加数据");                                    Thread.sleep(500);                                    lock.notifyAll();                                }                            } catch (InterruptedException e) {                                e.printStackTrace();                            }                        }                }            }        };        Runnable run2 = new Runnable() {            public void run() {                while(true){                    synchronized (lock) {                        try {                            if(list.size() <=0){                                lock.wait();                            }else{                                String str = list.removeFirst();                                System.out.println(Thread.currentThread().getName()+"获取数据"+str);                                Thread.sleep(500);                                lock.notifyAll();                            }                        } catch (InterruptedException e) {                            e.printStackTrace();                        }                    }                }            }        };        //定义一个缓存线程池,启动线程        ExecutorService executor = Executors.newCachedThreadPool();        executor.execute(run);        executor.execute(run);        executor.execute(run2);        executor.execute(run2);        executor.execute(run2);    }}
原创粉丝点击