zoukankan      html  css  js  c++  java
  • java多线程-Lock

    大纲:

    1. Lock接口
    2. synchronized&Lock异同

    一、Lock

    public interface Lock {
        void lock();
        void lockInterruptibly() throws InterruptedException;
        boolean tryLock();
        boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
        void unlock();
        Condition newCondition();
    }
    1. lock()获取锁。
    2. lockInterruptibly()可打断的获取锁方法,仅可打断等待锁的线程。
    3. tryLock()获取锁并返回结果,得到锁的线程返回true,没有拿到锁的线程不再等待并返回false。
    4. tryLock(time)带参数函数,可以传入一个时间,在这个时间内获得锁的线程返回true,没有获得锁返回false,且在这个时间内等在锁的线程可以被打断。
    5. unlock()释放锁。
    6. newCondition 创建一个场景(见下章)。

    例:

    ReentrantLock为Lock接口唯一实现类
     class Met  {
        Lock lock = new ReentrantLock();
    
        public void action() {
            String name = Thread.currentThread().getName()+":";
            try {
                lock.lockInterruptibly();
                try {
                    for (int i = 0; i < 1000; i++) {
                        System.out.println(name+i);
                    }
                }finally {
                    System.out.println(name+"unlock");
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                System.out.println(name+"interrupted");
            }
    
        }
    }
    public class MyRunnable implements Runnable {
        Met met;
        MyRunnable(Met met){
            this.met = met;
        }
        @Override
        public void run() {
             met.action(Thread.currentThread());
        }
    }
    class TestLock {
        public static void main(String[] args) {
            Met met = new Met();
            MyRunnable myRunnable = new MyRunnable(met);
            Thread thread0 = new Thread(myRunnable);
            Thread thread1 = new Thread(myRunnable);
            thread0.start();
            thread1.start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    二、synchronized&Lock异同

    1. synchronized代码块内发生异常,锁会自动释放、lock需要在finally中手动释放。
    2. synchronized无法锁的获取情况。
    3. synchronized无法设置超时。
    4. synchronized无法中断等待获取锁的线程。
    5. synchronized无法设置是否公平锁,lock和synchronized默认是非公平锁。
    6. lock和synchronized都是排他、重入锁。
  • 相关阅读:
    IntentService和AsyncTask的区别
    Android拒绝来电的实现ITelephony类的反射
    如何安全退出已调用多个Activity的Application?
    Android常用知识点总汇
    android menu的两种实现方法
    Android4.0系统接收不到广播的问题解析
    Android 面试题
    AsyncTask的用法
    select @@identity的用法
    按需操控Broadcast Receivers是否开启]
  • 原文地址:https://www.cnblogs.com/liuboyuan/p/10281505.html
Copyright © 2011-2022 走看看