题目:
三个线程交替输出0到75,即线程A输出0,线程B输出1,线程C输出2,线程A输出3…
思路:
由于三个线程一次只能有一个在打印数字,所以需要用一个锁来进行同步。打印时需要保证线程的执行顺序,所以,线程A执行完之后 不能唤醒全部线程,只能唤醒线程B。利用Condition实现,代码如下:
package com.primer.demo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class PrintNumber2 {
private static volatile int count = 0;
private static Lock lock = new ReentrantLock();
private static Condition a = lock.newCondition();
private static Condition b = lock.newCondition();
private static Condition c = lock.newCondition();
static class ThreadA implements Runnable{
@Override
public void run() {
try{
lock.lock();
while (count < 75){
while (count % 3 != 0){
a.await();
}
if (count > 75){
break;*//如果此处没有break,可能打印出76、77*
}
System.out.println(Thread.currentThread().getName() + " " + count);
count +=1;
b.signal();
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
static class ThreadB implements Runnable{
@Override
public void run() {
try{
lock.lock();
while (count < 75){
while (count % 3 != 1){
b.await();
}
if (count > 75){
break;
}
System.out.println(Thread.currentThread().getName() + " " + count);
count +=1;
c.signal();
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
static class ThreadC implements Runnable{
@Override
public void run() {
try{
lock.lock();
while (count < 75){
while (count % 3 != 2){
c.await();
}
if (count > 75){
break;
}
System.out.println(Thread.currentThread().getName() + " " + count);
count +=1;
a.signal();
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
new Thread(new ThreadA()).start();
new Thread(new ThreadB()).start();
new Thread(new ThreadC()).start();
}
}