您的位置:首页 > 编程语言 > Java开发

java学习笔记90--java.util.concurrent.locks.Lock接口

2019-03-24 12:56 183 查看

JDK5.0后新增了Lock接口,可以是用来实现synchronized关键字的作用,同时功能更加灵活和强大,ReentrantLock类是JDK中提供的Lock接口的默认实现
    1)Lock接口的lock()方法和unlock()方法
    例如:
    public class LockTest extends Thread{
        public static void main(String[] args) {
            class Run implements Runnable{
                private int i;
                private Lock lock = new ReentrantLock();
                public void run() {
                    for(int j=0;j<100000;j++){
                        lock.lock();
                        try {
                            i++;
                        } finally {
                            lock.unlock();
                        }
                    }
                }
                public int getValue(){
                    return i;
                }
            };
            
            Run run = new Run();
            Thread t1 = new Thread(run);
            Thread t2 = new Thread(run);
            Thread t3 = new Thread(run);
            Thread t4 = new Thread(run);
            
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            
            try {
                t1.join();
                t2.join();
                t3.join();
                t4.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("i = "+run.getValue());
        }
    }


    2)Lock接口的tryLock()方法
        尝试着去拿锁,如果拿到了就返回true否则返回false,注意这点和synchronized是不同的,如果是synchronized的话,如果尝试拿不到锁的话,那么当前线程就会变了阻塞状态(阻塞在锁池)

        此方法的典型使用语句如下:
        Lock lock = new ReentrantLock();
        if (lock.tryLock()) {
            try {
                //安全的同步操作
            } finally {
              lock.unlock();
            }
        } else {
            //拿不到锁就去做其他事情,但这里就不是线程同步了
        }

    例如:
    main:
        class Run implements Runnable{
            private Lock lock = new ReentrantLock();
            private int i;
            public void run() {
                boolean flag = true;
                String name = Thread.currentThread().getName();
                while(flag){
                    if (lock.tryLock()) {
                        try {
                            for(int j=0;j<1000;j++){
                                i++;
                            }
                        } finally {
                            System.out.println(name+": i = "+i);
                            flag = false;
                            lock.unlock();
                        }
                    } else {
                        System.out.println(name+": 郁闷了,没拿到锁,那么就睡会把");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        
        Runnable run = new Run();
        
        Thread t1 = new Thread(run);
        Thread t2 = new Thread(run);
        t1.start();
        t2.start();


    3)Lock接口的newCondition方法和Condition接口
        Condition接口表示一个条件,Lock接口的newCondition方法可以返回一个Condition接口的实现类对象,表示当前线程执行代码的条件。
        
        Condition接口中的await()方法,相当于Object中的wait方法
        Condition接口中的signal()方法,相当于Object中的notify()方法
        Condition接口中的signalAll()方法,相当于Object中的notifyAll()方法

        例如:这个是使用synchronized关键字实现的
        public static void main(String[] args) {
            Runnable run = new Runnable() {
                private int x;
                public void run() {
                    String name = Thread.currentThread().getName();
                    synchronized (this) {
                        for (int i = 0; i < 1000; i++) {
                            x++;
                        }
                        try {
                            this.notify();
                            this.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                        System.out.println(name+" x = "+x);
                        this.notifyAll();
                    }
                }
            };
            Thread t1 = new Thread(run);
            Thread t2 = new Thread(run);
            t1.start();
            t2.start();
        }
        
        例如:把上面的例子改为Lock和Condition实现
        public static void main(String[] args) {
            Runnable run = new Runnable() {
                private int x;
                private Lock lock = new ReentrantLock();
                private Condition con = lock.newCondition();
                public void run() {
                    String name = Thread.currentThread().getName();
                    lock.lock();
                    try {
                        for (int i = 0; i < 1000; i++) {
                            x++;
                        }
                        try {
                            con.signalAll();
                            con.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                        System.out.println(name+" x = "+x);
                        con.signalAll();
                    } finally {
                        lock.unlock();
                    }
                }
            };
            
            Thread t1 = new Thread(run);
            Thread t2 = new Thread(run);
            
            t1.start();
            t2.start();
            
        }

        
        注:俩种实现方法的效果是一样的,synchronized是java中的关键字,而Lock和Condition和JKD5.0新增的俩个接口,其结合着使用可以代替synchronized的功能,并且功能更加灵活和强大

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: