交替打印FooBar
方法1:信號量semaphore
- semaphore的使用簡介:http://www.reibang.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的使用簡介:http://www.reibang.com/p/333fd8faa56e
public class FooBar {
private int n;
public FooBar(int n) {
this.n = n;
}
CyclicBarrier cb = new CyclicBarrier(2); // 集齊2個線程調(diào)用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; // 表示當(dāng)前時間應(yīng)該打印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(); // 喚醒, 不釋放鎖; 一般喚醒代碼之后,會立即退出臨界區(qū), 從而釋放鎖
}
}
}
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(); // 喚醒, 不釋放鎖; 一般喚醒代碼之后刊殉,會立即退出臨界區(qū), 從而釋放鎖
}
}
}
}
打印零與奇偶數(shù)
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機(jī)器超時
- lock和condition.await/signal/signalAll,相比synchronized和wait/notify/notityAll實(shí)現(xiàn)類似的功能记焊,只不過一個lock可以生成多個condition對象逸月,所以可以精確地喚醒某個線程,synchronized關(guān)鍵字做不到的遍膜。
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循環(huán)中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();
}
}
當(dāng)然上面的程序稍加修改碗硬,可以只用兩個condition實(shí)現(xiàn)瓤湘,喚醒odd或者even線程的時候,可以不用精準(zhǔn)喚醒恩尾,改用全部喚醒弛说,因?yàn)閛dd和even線程都有自己的判斷條件,不滿足條件的線程會重新進(jìn)入await()翰意,此時另外一個正確的線程就會得到鎖進(jìn)行打幽救恕;
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關(guān)鍵字加wait,notityAll實(shí)現(xiàn)上面的功能
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();
}
}
}
}