ARTS-02.md

Algorithm

Print in Order(1114)

1
2
3
4
5
6
7
8
9
10
11
12
Suppose we have a class:

public class Foo {
  public void one() { print("one"); }
  public void two() { print("two"); }
  public void three() { print("three"); }
}
The same instance of Foo will be passed to three different threads. Thread A will call one(), thread B will call two(), and thread C will call three(). Design a mechanism and modify the program to ensure that two() is executed after one(), and three() is executed after two().

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路
leetcode关于多线程的新题,考察多线程中的按序执行。
可以用以下方法解:

  1. 利用CountDownLatch 来控制执行的顺序。
  2. 利用volatile 创建全局可见的变量,通过对该变量的原子性更新来保证执行顺序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.concurrent.CountDownLatch;

class Foo {
private CountDownLatch c2;
private CountDownLatch c3;

public Foo() {
c2 = new CountDownLatch(1);
c3 = new CountDownLatch(1);
}

public void first(Runnable printFirst) throws InterruptedException {

// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
c2.countDown();
}

public void second(Runnable printSecond) throws InterruptedException {
c2.await();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
c3.countDown();
}

public void third(Runnable printThird) throws InterruptedException {
c3.await();
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Foo {

private volatile int flag = 1;
public Foo() {

}

public void first(Runnable printFirst) throws InterruptedException {

// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
flag = 2;
}

public void second(Runnable printSecond) throws InterruptedException {
while(flag != 2);
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
flag = 3;
}

public void third(Runnable printThird) throws InterruptedException {
while(flag != 3);
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}

Reading

Faircode, an alternative to Open Source that aims to get developers paid
https://hackernoon.com/faircode-an-alternative-to-open-source-89cdc65df3fa

在2017年作者提出了Faircode这个概念,旨在给开发者一个新的盈利方式。不同于“闭源软件”,Faircode 打算以向大公司收费而对小公司免费的形势获利。然而不幸的是,作者发起的Faircode 及相关的license 已经被删除了。作者想法在当时比较前卫,可能在推行的过程中成效不大吧。

Tip

https://javarevisited.blogspot.com/2018/05/10-tips-to-become-better-java-developer.html

Share

JAVA 注解的基本原理

https://juejin.im/post/5b45bd715188251b3a1db54f