{"action":"created","issue":{"url":"https://api.github.com/repos/pzxwhc/MineKnowContainer/issues/16","repository_url":"https://api.github.com/repos/pzxwhc/MineKnowContainer","labels_url":"https://api.github.com/repos/pzxwhc/MineKnowContainer/issues/16/labels{/name}","comments_url":"https://api.github.com/repos/pzxwhc/MineKnowContainer/issues/16/comments","events_url":"https://api.github.com/repos/pzxwhc/MineKnowContainer/issues/16/events","html_url":"https://github.com/pzxwhc/MineKnowContainer/issues/16","id":140669315,"number":16,"title":"Java 多线程：Lock接口（接口方法分析，ReentrantLock，ReadWriteLock）","user":{"login":"pzxwhc","id":9150767,"avatar_url":"https://avatars.githubusercontent.com/u/9150767?v=3","gravatar_id":"","url":"https://api.github.com/users/pzxwhc","html_url":"https://github.com/pzxwhc","followers_url":"https://api.github.com/users/pzxwhc/followers","following_url":"https://api.github.com/users/pzxwhc/following{/other_user}","gists_url":"https://api.github.com/users/pzxwhc/gists{/gist_id}","starred_url":"https://api.github.com/users/pzxwhc/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/pzxwhc/subscriptions","organizations_url":"https://api.github.com/users/pzxwhc/orgs","repos_url":"https://api.github.com/users/pzxwhc/repos","events_url":"https://api.github.com/users/pzxwhc/events{/privacy}","received_events_url":"https://api.github.com/users/pzxwhc/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":8,"created_at":"2016-03-14T13:11:40Z","updated_at":"2016-12-07T09:48:38Z","closed_at":null,"body":"# 前言\n\n当我们了解了 [多线程生成的原因](https://github.com/pzxwhc/MineKnowContainer/issues/6) 之后，会有相应的解决办法，最典型的就是 [synchronized](https://github.com/pzxwhc/MineKnowContainer/issues/7) 和 lock。lock可以说是 synchronized 的一个替代品，synchronized 能做的事，lock 基本都可以做，而且能做得更好。他们的一些区别是：\n- **lock在获取锁的过程可以被中断。**\n- **lock可以尝试获取锁，如果锁被其他线程持有，则返回 false，不会使当前线程休眠。**\n- **lock在尝试获取锁的时候，传入一个时间参数，如果在这个时间范围内，没有获得锁，那么就是终止请求。**\n- **synchronized 会自动释放锁，lock 则不会自动释放锁。**\n\n这样可以看到，lock 比起 synchronized 具有更细粒度的控制。但是也不是说 lock 就完全可以取代 synchronized，因为 lock 的学习成本，复杂度等方面要比 synchronized 高，对于初级 java 程序员，使用 synchronized 的风险要比 lock 低。\n# 目录\n\n包括了：\n- Lock 接口方法分析\n- RentrantLock\n- ReadWriteLock\n# Java Lock接口源码分析\n\nLock 接口方法如下：\n\n```\npublic interface Lock {\n    void lock();\n    void lockInterruptibly() throws InterruptedException;\n    boolean tryLock();\n    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;\n    void unlock();\n    Condition newCondition();\n}\n```\n## lock，unlock 方法\n\nlock() 可以用于对一段代码进行加锁，这样别的代码在锁释放之前需要进行等待，需要注意，**_lock不会像 synchronized 那样自动释放锁**_，所以：**_一定要放在 try-finally块中，保证锁的释放。**_ 例如：\n\n```\ntry {\n    lock.lock();\n    ......\n} finally {\n    lock.unlock();  \n}\n```\n## tryLock 方法\n- tryLock()：尝试获得锁，如果成功，返回 true，否则，返回 false。\n- tryLock(long time,TimeUnit unit)：在一定的时间内尝试获得锁，并且在这段时间直接可以被打断。如果成功获得，那么将返回 true，否则，返回 false。\n## lockInterruptibly 方法\n\n这里首先需要了解两个概念才能更好的理解这个方法：\n- 线程的打扰机制\n- Thread类的interrupt,interrupted,isInterrupted方法的区别\n\n对于线程的打扰机制，**_每个线程都有一个打扰标志。**_ \n- 如果线程在sleep或wait,join，此时如果别的进程调用此进程的 interrupt（）方法，此线程会被唤醒并被要求处理InterruptedException；\n- 如果线程在运行，则不会收到提醒。但是 此线程的 “打扰标志”会被设置。\n\n所以说，对于 interrupt() 方法：\n- **_不会中断一个正在运行的线程**_。\n- **_不会中断一个正在运行的线程**_。\n- **_不会中断一个正在运行的线程**_。\n\n对于 interrupt,interrupted,isInterrupted方法的区别：\n\ninterrupt 方法上面有说到了。对于 interrupted 和 isInterrupted 方法,stackoverflow 说得很好了：\n\n```\ninterrupted() is static and checks the current thread. isInterrupted() is an instance method which checks the Thread object that it is called on.\n\nA common error is to call a static method on an instance.\n\nThread myThread = ...;\nif (myThread.interrupted()) {} // WRONG! This might not be checking myThread.\nif (myThread.isInterrupted()) {} // Right!\n\nAnother difference is that interrupted() also clears the status of the current thread. In other words, if you call it twice in a row and the thread is not interrupted between the two calls, the second call will return false even if the first call returned true.\n\nThe Javadocs tell you important things like this; use them often!\n```\n\n下面再介绍下 lockInterruptibly 方法：\n\n当通过这个方法去获取锁时，如果线程正在等待获取锁，则这个线程能够响应中断，即中断线程的等待状 态。例如当两个线程同时通过lock.lockInterruptibly()想获取某个锁时，假若此时线程A获取到了锁，而线程B只有在等待，那 么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程。\n## newCondition()\n\n用于获取一个 Conodition 对象。Condition 对象是比 Lock 更细粒度的控制。要很好的理解 condition，个人觉得必须要知道，[生产者消费者问题](https://github.com/pzxwhc/MineKnowContainer/issues/8)。\n\n简单来说就是，我们都了解 生成者在缓冲区满了的时候需要休眠，此时会再唤起一个线程，那么你此时唤醒的是生成者还是消费者呢，如果是消费者，很好；但是如果是唤醒生产者，那还要再休眠，此时就浪费资源了。condition就可以用来解决这个问题，能保证每次唤醒的都是消费者。具体参考：[Java 多线程：condition关键字 ](https://github.com/pzxwhc/MineKnowContainer/issues/10)\n\nlock 方法大体就介绍到这里。\n# ReentrantLock\n\n可重入锁：指同一个线程，外层函数获得锁之后，内层递归函数仍有获得该锁的代码，但是不受影响。\n\n**_可重入锁的最大作用就是 可以避免死锁。**_例如：A线程 有两个方法 a 和 b，其中 a 方法会调用 b 方法，假如 a，b 两个方法都需要获得锁，那么首先 a 方法先执行，会获得锁，此时 b方法将永远获得不了锁，b 方法将一直阻塞住， a 方法由于 b 方法没有执行完，它本身也 不释放锁，此时就会造成一个 死锁。\nReentrantLock 就是一个可重入锁。真正使用 锁的时候，一般是 Lock lock ＝ new ReentrantLock()；然后 使用 Lock 接口方法。\n# ReadWriteLock\n\n接口代码如下：\n\n```\npublic interface ReadWriteLock {  \n    Lock readLock();  \n    Lock writeLock();  \n}  \n```\n\nReadWriteLock 可以算是 Lock 的一个细分，合理使用有利于提高效率。比如说， 对于一个变量 i， A，B 线程同时读，那么不会造成错误的结果，所以此时是允许并发，但是如果是同时写操作，那么则是有可能造成错误。所以真正使用的时候，可以使用 细分需要的是读锁还是写锁，再相应地进行加锁。\n\nPs：**_从代码也可以看出，ReadWriteLock 和 Lock 没有关系，既不继承，也不是实现。**_\n# 参考\n- [Java 理论与实践: JDK 5.0 中更灵活、更具可伸缩性的锁定机制](https://www.ibm.com/developerworks/cn/java/j-jtp10264/)\n- [Java中Lock，tryLock，lockInterruptibly有什么区别?](https://www.zhihu.com/question/36771163/answer/68974735)\n- [Thread类的interrupt,interrupted,isInterrupted方法的理解](http://macleo.iteye.com/blog/626283)\n- [Java多线程sleep(),join(),interrupt(),wait(),notify()](http://www.blogjava.net/fhtdy2004/archive/2009/06/08/280728.html)\n# 写在最后\n1. 写出来，说出来才知道对不对，知道不对才能改正，改正了才能成长。\n2. 在技术方面，希望大家眼里都容不得沙子。如果有不对的地方或者需要改进的地方希望可以指出，万分感谢。\n"},"comment":{"url":"https://api.github.com/repos/pzxwhc/MineKnowContainer/issues/comments/265402686","html_url":"https://github.com/pzxwhc/MineKnowContainer/issues/16#issuecomment-265402686","issue_url":"https://api.github.com/repos/pzxwhc/MineKnowContainer/issues/16","id":265402686,"user":{"login":"IAdair","id":16718550,"avatar_url":"https://avatars.githubusercontent.com/u/16718550?v=3","gravatar_id":"","url":"https://api.github.com/users/IAdair","html_url":"https://github.com/IAdair","followers_url":"https://api.github.com/users/IAdair/followers","following_url":"https://api.github.com/users/IAdair/following{/other_user}","gists_url":"https://api.github.com/users/IAdair/gists{/gist_id}","starred_url":"https://api.github.com/users/IAdair/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/IAdair/subscriptions","organizations_url":"https://api.github.com/users/IAdair/orgs","repos_url":"https://api.github.com/users/IAdair/repos","events_url":"https://api.github.com/users/IAdair/events{/privacy}","received_events_url":"https://api.github.com/users/IAdair/received_events","type":"User","site_admin":false},"created_at":"2016-12-07T09:48:38Z","updated_at":"2016-12-07T09:48:38Z","body":"你们都好厉害"}}
{"actor":{"display_login":"IAdair"}}