题目描述:
启动三个线程,线程1打印a,线程2打印b,线程3打印c,依次打印15次。
Lock Condition实现
代码如下:
public class NAbcPrinter {
private final Lock lock = new ReentrantLock();
private final Condition con1 = lock.newCondition();
private final Condition con2 = lock.newCondition();
private final Condition con3 = lock.newCondition();
private int no = 1;
public void process1() {
lock.lock();
try {
while (no != 1) con1.await();
System.out.println(Thread.currentThread().getName() + " a");
no = 2;
con2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void process2() {
lock.lock();
try {
while (no != 2) con2.await();
System.out.println(Thread.currentThread().getName() + " b");
no = 3;
con3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void process3() {
lock.lock();
try {
while (no != 3) con3.await();
System.out.println(Thread.currentThread().getName() + " c");
no = 1;
con1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
NAbcPrinter p = new NAbcPrinter();
new Thread(() -> {
for (int i = 0; i < 15; i++) p.process1();
}).start();
new Thread(() -> {
for (int i = 0; i < 15; i++)
p.process2();
}).start();
new Thread(() -> {
for (int i = 0; i < 15; i++)
p.process3();
}).start();
}
}
阻塞队列实现:
public class AbcPrinter {
private final BlockingQueue<Integer> bq1 = new ArrayBlockingQueue<>(1);
private final BlockingQueue<Integer> bq2 = new ArrayBlockingQueue<>(1);
private final BlockingQueue<Integer> bq3 = new ArrayBlockingQueue<>(1);
{
try {
bq1.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void process1() {
try {
bq1.take();
System.out.println(Thread.currentThread().getName() + " a");
bq2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void process2() {
try {
bq2.take();
System.out.println(Thread.currentThread().getName() + " b");
bq3.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void process3() {
try {
bq3.take();
System.out.println(Thread.currentThread().getName() + " c");
bq1.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
NAbcPrinter p = new NAbcPrinter();
new Thread(() -> {
for (int i = 0; i < 15; i++) p.process1();
}).start();
new Thread(() -> {
for (int i = 0; i < 15; i++)
p.process2();
}).start();
new Thread(() -> {
for (int i = 0; i < 15; i++)
p.process3();
}).start();
}
}