交替打印FooBar
方法1:信号量semaphore
- semaphore的使用简介:https://www.jianshu.com/p/ec637f835e08
class FooBar {
private int n;
public FooBar(int n) {
this.n = n;
}
Semaphore foo = new Semaphore(1);
Semaphore bar = new Semaphore(0);
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
foo.acquire();
printFoo.run();
bar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
bar.acquire();
printBar.run();
foo.release();
}
}
}
方法2:CyclicBarrier
- CyclicBarrier的使用简介:https://www.jianshu.com/p/333fd8faa56e
public class FooBar {
private int n;
public FooBar(int n) {
this.n = n;
}
CyclicBarrier cb = new CyclicBarrier(2); // 集齐2个线程调用await时开栅放行
volatile boolean foo = true;
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while (!foo) ;
printFoo.run();
foo = false;
try {
cb.await();
} catch (BrokenBarrierException e) {
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
try {
cb.await();
} catch (BrokenBarrierException e) {
}
printBar.run();
foo = true;
}
}
}
方法3:synchronized
- synchronized 用法:https://www.cnblogs.com/fnlingnzb-learner/p/10335662.html
- Object.wait, notity, notifyAll的用法:https://www.cnblogs.com/moongeek/p/7631447.html
class FooBar {
private int n;
public FooBar(int n) {
this.n = n;
}
private boolean foo = true; // 表示当前时间应该打印foo/bar
private Object lock = new Object();
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (lock) {
if (!foo) {
lock.wait(); // 等待并且释放锁
}
foo = false;
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
lock.notifyAll(); // 唤醒, 不释放锁; 一般唤醒代码之后,会立即退出临界区, 从而释放锁
}
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
synchronized (lock) {
if (foo) {
lock.wait(); // 等待并且释放锁
}
foo = true;
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
lock.notifyAll(); // 唤醒, 不释放锁; 一般唤醒代码之后,会立即退出临界区, 从而释放锁
}
}
}
}
打印零与奇偶数
semaphore信号量
class ZeroEvenOdd {
private int n;
private Semaphore zero = new Semaphore(1);
private Semaphore even = new Semaphore(0);
private Semaphore odd = new Semaphore(0);
public ZeroEvenOdd(int n) {
this.n = n;
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void zero(IntConsumer printNumber) throws InterruptedException {
for (int i=1;i<=n;i++){
zero.acquire();
printNumber.accept(0);
if(i%2==1){
odd.release();
}else{
even.release();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
for (int i=2;i<=n;i+=2){
even.acquire();
printNumber.accept(i);
zero.release();
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
for (int i=1;i<=n;i+=2){
odd.acquire();
printNumber.accept(i);
zero.release();
}
}
}
Lock和Condition
- 本地测试可通过,leetcode机器超时
- lock和condition.await/signal/signalAll,相比synchronized和wait/notify/notityAll实现类似的功能,只不过一个lock可以生成多个condition对象,所以可以精确地唤醒某个线程,synchronized关键字做不到的。
public class ZeroEvenOdd {
// 0, 1, 0, 2, 0, 3, 0, 4, ..., 0, n
// 1, 2, 3, 4, 5, 6, 7, 8, ..., 2n-1, 2n
private int n;
private volatile int count;
private Lock lock = new ReentrantLock();
private Condition waitForZero = lock.newCondition();
private Condition waitForEven = lock.newCondition();
private Condition waitForOdd = lock.newCondition();
public ZeroEvenOdd(int n) {
this.n = n;
this.count = 1;
}
public void zero(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
try {
lock.lock();
while (count % 2 == 0){
waitForZero.await();
}
if(count > 2 * n){
break; // 尽管while循环中count满足条件, 但是在线程唤醒之后, 其它线程改变了count值, 所以必须再加一个判断
}
printNumber.accept(0);
count++;
if(count / 2 % 2 == 1){
waitForOdd.signal();
}else {
waitForEven.signal();
}
} finally {
lock.unlock();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
try {
lock.lock();
while (count % 2 == 1 || count / 2 % 2 == 1){
waitForEven.await();
}
if(count > 2 * n){
break;
}
printNumber.accept(count / 2);
count++;
waitForZero.signal();
} finally {
lock.unlock();
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
try {
lock.lock();
while (count % 2 == 1 || count / 2 % 2 == 0){
waitForOdd.await();
}
if(count > 2 * n){
break;
}
printNumber.accept(count / 2);
count++;
waitForZero.signal();
} finally {
lock.unlock();
}
}
}
// 本地测试
public static void main(String[] args) {
ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(10);
new Thread(new Runnable() {
@Override
public void run() {
try {
zeroEvenOdd.zero(value -> System.out.println(value));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
zeroEvenOdd.even(value -> System.out.println(value));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
zeroEvenOdd.odd(value -> System.out.println(value));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
当然上面的程序稍加修改,可以只用两个condition实现,唤醒odd或者even线程的时候,可以不用精准唤醒,改用全部唤醒,因为odd和even线程都有自己的判断条件,不满足条件的线程会重新进入await(),此时另外一个正确的线程就会得到锁进行打印;
public class ZeroEvenOdd {
// 0, 1, 0, 2, 0, 3, 0, 4, ..., 0, n
// 1, 2, 3, 4, 5, 6, 7, 8, ..., 2n-1, 2n
private int n;
private volatile int count;
private Lock lock = new ReentrantLock();
private Condition waitForZero = lock.newCondition();
private Condition waitForEvenOrOdd = lock.newCondition();
public ZeroEvenOdd(int n) {
this.n = n;
this.count = 1;
}
public void zero(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
try {
lock.lock();
while (count % 2 == 0){
waitForZero.await();
}
if(count > 2 * n){
break;
}
printNumber.accept(0);
count++;
waitForEvenOrOdd.signalAll(); // 全部唤醒, 不用精确唤醒
} finally {
lock.unlock();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
try {
lock.lock();
while (count % 2 == 1 || count / 2 % 2 == 1){
waitForEvenOrOdd.await();
}
if(count > 2 * n){
break;
}
printNumber.accept(count / 2);
count++;
waitForZero.signal();
} finally {
lock.unlock();
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
try {
lock.lock();
while (count % 2 == 1 || count / 2 % 2 == 0){
waitForEvenOrOdd.await();
}
if(count > 2 * n){
break;
}
printNumber.accept(count / 2);
count++;
waitForZero.signal();
} finally {
lock.unlock();
}
}
}
}
同理可用synchronized关键字加wait,notityAll实现上面的功能
public class ZeroEvenOdd {
// 0, 1, 0, 2, 0, 3, 0, 4, ..., 0, n
// 1, 2, 3, 4, 5, 6, 7, 8, ..., 2n-1, 2n
private int n;
private volatile int count;
public ZeroEvenOdd(int n) {
this.n = n;
this.count = 1;
}
public void zero(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
synchronized (this){
while (count % 2 == 0){
this.wait();
}
if(count > 2 * n){
break;
}
printNumber.accept(0);
count++;
this.notifyAll();
}
}
}
public void even(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
synchronized (this){
while (count % 2 == 1 || count / 2 % 2 == 1){
this.wait();
}
if(count > 2 * n){
break;
}
printNumber.accept(count / 2);
count++;
this.notifyAll();
}
}
}
public void odd(IntConsumer printNumber) throws InterruptedException {
while (count <= 2 * n){
synchronized (this){
while (count % 2 == 1 || count / 2 % 2 == 0){
this.wait();
}
if(count > 2 * n){
break;
}
printNumber.accept(count / 2);
count++;
this.notifyAll();
}
}
}
}