Java实现多线程交替打印ABC
实现java通4个线程顺序打印ABC四个字母,第一个线程打印A,第二个线程打印B,第三个线程打印C,每个线程打印10次
基于synchronized+wait/notify
public class printABC {
private volatile static int state = 0;
private static final Object lock = new Object();
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
lock.lock();
Thread A = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
synchronized (lock){
while (state%3!=0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
state++;
lock.notifyAll();
}
}
}
});
Thread B = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
synchronized(lock){
while (state%3!=1){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
state++;
lock.notifyAll();
}
}
}
});
Thread C = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
synchronized(lock){
while (state%3!=2){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
state++;
lock.notifyAll();
}
}
}
});
A.start();
B.start();
C.start();
}
}
基于ReentrantLock+Condition
实现方式如下,可以看到核心方法为将wait和notifyAll转换为await和signal,好处是可以做特定线程的唤醒。最后因为增加的是reetrantLock锁,所以要在finally代码块中对lock对象进行解锁
public class MultiConditionPrintABC {
private static Lock lock = new ReentrantLock();
private static Condition conditionA = lock.newCondition();
private static Condition conditionB = lock.newCondition();
private static Condition conditionC = lock.newCondition();
private static int state = 0;
static class ThreadA implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (state % 3 != 0) {
conditionA.await();
}
System.out.print("A");
state++;
conditionB.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
static class ThreadB implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (state % 3 != 1) {
conditionB.await();
}
System.out.print("B");
state++;
conditionC.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
static class ThreadC implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (state % 3 != 2) {
conditionC.await();
}
System.out.print("C");
state++;
conditionA.signal();
} catch (InterruptedException 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();
}
}