交替输出
题目:线程 1 输出 a 5 次,线程 2 输出 b 5 次,线程 3 输出 c 5 次。现在要求输出 abcabcabcabcabc
wait notify 版
public class SyncWaitNotify {
private volatile int flag;
private volatile int loopNumber;
public SyncWaitNotify(int flag,int loopNumber){
this.flag = flag;
this.loopNumber = loopNumber;
}
public void print(int flag,int next,String str){
for(int i=0;i<loopNumber;i++){
synchronized (this){
while (this.flag != flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(str);
this.flag = next;
this.notifyAll();
}
}
}
public static void main(String[] args) {
SyncWaitNotify syncWaitNotify = new SyncWaitNotify(1,5);
new Thread(() -> {
syncWaitNotify.print(1,2,"a");
}).start();
new Thread(() -> {
syncWaitNotify.print(2,3,"b");
}).start();
new Thread(() -> {
syncWaitNotify.print(3,1,"c");
}).start();
}
}
Lock 条件变量版
public class AwaitSignal extends ReentrantLock {
private volatile int loopNumber;
public AwaitSignal(int loopNumber) {
this.loopNumber = loopNumber;
}
public void print(Condition condition,Condition next,String str){
for(int i=0;i<loopNumber;i++){
this.lock();
try {
try {
condition.await();
System.out.print(str);
next.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
this.unlock();
}
}
}
public void start(Condition condition){
this.lock();
try {
condition.signal();
} finally {
this.unlock();
}
}
public static void main(String[] args) {
AwaitSignal awaitSignal = new AwaitSignal(5);
Condition aWait = awaitSignal.newCondition();
Condition bWait = awaitSignal.newCondition();
Condition cWait = awaitSignal.newCondition();
new Thread(() -> {
awaitSignal.print(aWait,bWait,"a");
}).start();
new Thread(() -> {
awaitSignal.print(bWait,cWait,"b");
}).start();
new Thread(() -> {
awaitSignal.print(cWait,aWait,"c");
}).start();
awaitSignal.start(aWait);
}
}
Park Unpark 版
public class SyncPark {
private int loopNumber;
public Thread[] threads;
public SyncPark(int loopNumber){
this.loopNumber = loopNumber;
}
public void print(int next,String str){
for(int i=0;i<loopNumber;i++){
LockSupport.park();
System.out.print(str);
LockSupport.unpark(threads[next]);
}
}
public void start(Thread thread){
LockSupport.unpark(thread);
}
public static void main(String[] args) {
SyncPark syncPark = new SyncPark(5);
Thread t1 = new Thread(() -> {
syncPark.print(1, "a");
}, "t1");
Thread t2 = new Thread(() -> {
syncPark.print(2, "b");
}, "t2");
Thread t3 = new Thread(() -> {
syncPark.print(0, "c");
}, "t3");
syncPark.threads = new Thread[]{t1,t2,t3};
t1.start();
t2.start();
t3.start();
syncPark.start(t1);
}
}