方法一:通过可重入锁进行定向唤醒
package com.justalk.javademo.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//三个线程循环按顺序进行打印A,B,C
public class ReentrantLockPrinter {
static ReentrantLock reentrantLock = new ReentrantLock();
public static void main(String[] args) {
Condition condition1 = reentrantLock.newCondition();
Condition condition2 = reentrantLock.newCondition();
Condition condition3 = reentrantLock.newCondition();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
System.out.println("A");
condition2.signal();
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
reentrantLock.unlock();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
System.out.println("B");
condition3.signal();
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
reentrantLock.unlock();
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
reentrantLock.lock();
System.out.println("C");
condition1.signal();
try {
condition3.await();
reentrantLock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadA.start();
threadB.start();
threadC.start();
}
}
方法二:通过对象锁锁住线程对象和唤醒
package com.justalk.javademo.thread;
public class Sync {
public static void main(String[] args) {
threadC.start();
threadB.start();
threadA.start();
}
static Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("A");
Sync.notify(threadB);
Sync.wait(threadA);
}
}
});
static Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("B");
Sync.notify(threadC);
Sync.wait(threadB);
}
}
});
static Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("C");
Sync.notify(threadA);
Sync.wait(threadC);
}
}
});
static void wait(Object o) {
synchronized (o) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static void notify(Object o) {
synchronized (o) {
o.notify();
}
}
}