前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode并发题目解题报告JAVA版

leetcode并发题目解题报告JAVA版

作者头像
公众号_松华说
修改2019-08-04 11:29:55
6010
修改2019-08-04 11:29:55
举报
文章被收录于专栏:松华说松华说

一、Print in Order

Suppose we have a class:

代码语言:javascript
复制
public class Foo {  public void first() { print("first"); }  public void second() { print("second"); }  public void third() { print("third"); }}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Example 1: Input: [1,2,3] Output: "firstsecondthird" Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.

方法1:信号量。semaphore和mutex都是内核对象,都可用于进程间的同步,并且都特别占用系统资源,区别是,mutex只能由一个线程(进行)访问被保护的资源。semaphore 是一种带计数的mutex的锁定,可定义同时访问被保护的资源的线程数

方法2:原子类AtomicInteger。AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减

方法3:倒计时器CountDownLatch,参考方法2。在多线程协作完成业务功能时,CountDownLatch能让我们很轻松实现下面这个需求,当需要等待其他多个线程完成任务之后,主线程才能继续往下执行业务功能

二、Print FooBar Alternately

Suppose you are given the following code:

代码语言:javascript
复制
class FooBar {  public void foo() {    for (int i = 0; i < n; i++) {      print("foo");    }  }  public void bar() {    for (int i = 0; i < n; i++) {      print("bar");    }  }}

The same instance of FooBar will be passed to two different threads. Thread A will call foo()while thread B will call bar(). Modify the given program to output "foobar" n times. Example 2: Input: n = 2 Output: "foobarfoobar" Explanation: "foobar" is being output 2 times.

这题其实是题目一的升级版,也可以使用信号量来轻松完成,这里给出其他解法

线程问题无非是要保证一致性、有序性和避免死锁,可见性可以使用volatile来保证,有序性可以使用锁来保证,死锁问题我们可以打破死锁的条件,也就是需要批量申请好资源或者按顺序获取到所有资源后才算获取到锁,比如

但是上面的示例无法满足本题要求,当n=1时输出结果可能是foobar也可以是barfoo,同理n=k时也会有顺序性问题,看似通过add和remove字符串顺序来解决,但是没有达到效果,具体分析过程留给读者完成

我们换种方法来完成,使用标准的生产-消费模型

这里需要注意的几个点: 1、初学者理解wait()的时候都认为是将当前线程阻塞,所以Thread.currentThread().wait();视乎很有道理。但是不知道大家有没有发现,在JDK类库中wait()和notify()方法并不是Thread类的,而是Object()中的。在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,当前线程等待 2、始终使用while循环来调用wait方法,永远不要在循环外调用wait方法,这样做的原因是尽管并不满足条件,但是由于其他线程调用notifyAll方法会导致被阻塞线程意外唤醒,此时执行条件不满足,它会导致约束失效 3、唤醒线程,应该使用notify还是notifyAll?notify会随机通知等待队列中的一个线程,而notifyAll会通知等待队列中所有线程,可知notify是有风险的 ,可能导致某些线程永远不会被通知到 4、当前线程必须拥有此对象监视器,然后才可以放弃对此监视器的所有权并等待 ,直到其他线程通过调用notify方法或notifyAll方法通知在此对象的监视器上等待的线程醒来,然后该线程将等到重新获得对监视器的所有权后才能继续执行。否则会报IllegalMonitorStateException 错误

不过Object的wait\notify\notifyAll原理是基于内核中的对象监视器Monitor完成的,有可能导致大量的上下文切换。为了更好的性能,往往使用基于AQS的显示锁ReetrantLock中的成员变量ConditionObject代替

AQS中存在一个同步队列,当一个线程没有获取到锁时就会进入到同步队列中进行阻塞,如果被唤醒后获取到销,则移出同步队列。另外AQS中还存在一个条件队列,通过addWaiter方法,可以将wait()方法调用的线程放入到条件队列中,线程进入等待状态,当调用signal或者signalAll方法时,线程就会被唤醒,之后进入到同步队列中。其中条件队列是通过链表实现的,所以可以支持多个等待队列。也就是说使用基于AQS接口的await\signal\signalAll原理是基于JAVA代码层实现的,性能有更大的优势

所以本题的另外一种写法是

三、Print Zero Even Odd

Suppose you are given the following code:

代码语言:javascript
复制
class ZeroEvenOdd {  public ZeroEvenOdd(int n) { ... }      // constructor  public void zero(printNumber) { ... }  // only output 0's  public void even(printNumber) { ... }  // only output even numbers  public void odd(printNumber) { ... }   // only output odd numbers}
代码语言:javascript
复制

The same instance of ZeroEvenOdd will be passed to three different threads:

  1. Thread A will call zero() which should only output 0's.
  2. Thread B will call even() which should only ouput even numbers.
  3. Thread C will call odd() which should only output odd numbers. Each of the thread is given a printNumbermethod to output an integer. Modify the given program to output the series 010203040506… where the length of the series must be 2n.

Example 1: Input: n = 2 Output: "0102" Explanation: There are three threads being fired asynchronously. One of them calls zero(), the other calls even(), and the last one calls odd(). "0102" is the correct output. Example 2: Input: n = 5 Output: "0102030405"

提示:使用信号量

四、Building H2O

There are two kinds of threads, oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given a releaseHydrogen and releaseOxygen method respectfully, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must be able to immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do. In other words:

  • If an oxygen thread arrives at the barrier when no hydrogen threads are present, it has to wait for two hydrogen threads.
  • If a hydrogen thread arrives at the barrier when no other threads are present, it has to wait for an oxygen thread and another hydrogen thread. We don’t have to worry about matching the threads up explicitly; that is, the threads do not necessarily know which other threads they are paired up with. The key is just that threads pass the barrier in complete sets; thus, if we examine the sequence of threads that bond and divide them into groups of three, each group should contain one oxygen and two hydrogen threads. Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.

Example 1: Input: "HOH" Output: "HHO" Explanation: "HOH" and "OHH" are also valid answers.

作者BLOG: www.liangsonghua.me

作者介绍:京东资深工程师-梁松华,在稳定性保障、敏捷开发、JAVA高级、微服务架构方面有深入的理解

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 松华说 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 二、Print FooBar Alternately
  • 四、Building H2O
相关产品与服务
项目管理
CODING 项目管理(CODING Project Management,CODING-PM)工具包含迭代管理、需求管理、任务管理、缺陷管理、文件/wiki 等功能,适用于研发团队进行项目管理或敏捷开发实践。结合敏捷研发理念,帮助您对产品进行迭代规划,让每个迭代中的需求、任务、缺陷无障碍沟通流转, 让项目开发过程风险可控,达到可持续性快速迭代。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档