线程一输出a,5次;
线程二输出b,5次;
线程三输出c,5次;
现在要求输出abcabcabcabcabc怎么实现?
采用wait和notifyAll实现
public class ThreadTest {public static void main(String[] args) {WaitNotify waitNotify = new WaitNotify(1, 5);new Thread(() -> waitNotify.print("a", 1, 2), "t1").start();new Thread(() -> waitNotify.print("b", 2, 3), "t2").start();new Thread(() -> waitNotify.print("c", 3, 1), "t3").start();}
}class WaitNotify {public void print(String str, int waitFlag, int nextFlag) {//t1线程启动,有五次循环,只有第一次满足条件输出a,flag=2,剩下的四次循环变成四个线程处于等待状态//t2线程启动,有五次循环,只有第一次满足条件输出b,flag=3,剩下的四次循环变成四个线程处于等待状态//t3线程启动,有五次循环,只有第一次满足条件输出c,flag=1,剩下的四次循环变成四个线程处于等待状态//t1线程上次处于等待的四个线程中的第一个线程满足条件输出a,flag=2,剩下三次循环变成三个线程处于等待状态//t2线程上次处于等待的四个线程中的第一个线程满足条件输出b,flag=3,剩下三次循环变成三个线程处于等待状态//t3线程上次处于等待的四个线程中的第一个线程满足条件输出c,flag=1,剩下三次循环变成三个线程处于等待状态//依此类推...for (int i = 0; i < loopNumber; i++) {synchronized (this) {while (flag != waitFlag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.print(str);flag = nextFlag;this.notifyAll();}}}//等待标记private int flag;//循环次数private int loopNumber;public WaitNotify(int flag, int loopNumber) {this.flag = flag;this.loopNumber = loopNumber;}
}
采用await和signal方法实现
public class ThreadTest2 {public static void main(String[] args) {AwaitSignal awaitSignal = new AwaitSignal(5);//存放t1线程中a字符串的条件集合Condition condition1 = awaitSignal.newCondition();//存放t2线程中a字符串的条件集合Condition condition2 = awaitSignal.newCondition();//存放t3线程中a字符串的条件集合Condition condition3 = awaitSignal.newCondition();new Thread(() -> awaitSignal.print("a", condition1, condition2), "t1").start();new Thread(() -> awaitSignal.print("b", condition2, condition3), "t2").start();new Thread(() -> awaitSignal.print("c", condition3, condition1), "t3").start();//休息1s,让上面三个线程各自进入各自的条件集合等待try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}//主线程唤醒第一个条件集合awaitSignal.lock();try {condition1.signal();}finally {awaitSignal.unlock();}}
}class AwaitSignal extends ReentrantLock{//输出次数private int loop;public AwaitSignal(int loop) {this.loop = loop;}public void print(String str, Condition current, Condition next) {for (int i = 0; i < loop; i++) {this.lock();try {try {//进入当前条件集合等待current.await();System.out.print(str);} catch (InterruptedException e) {e.printStackTrace();}//唤醒下一个条件集合next.signal();}finally {this.unlock();}}}
}
采用park和unpark方法实现
public class ParkUnParkDemo {static Thread t1;static Thread t2;static Thread t3;public static void main(String[] args) {PrakUnpak prakUnpak = new PrakUnpak(5);t1 = new Thread(() -> {prakUnpak.print("a", t2);}, "t1");t2 = new Thread(() -> {prakUnpak.print("b", t3);}, "t2");t3 = new Thread(() -> {prakUnpak.print("c", t1);}, "t3");t1.start();t2.start();t3.start();//唤醒t1线程LockSupport.unpark(t1);}
}class PrakUnpak {private int loopCount;public PrakUnpak(int loopCount) {this.loopCount = loopCount;}public void print(String text, Thread next) {for (int i = 0; i < loopCount; i++) {LockSupport.park();System.out.print(text);LockSupport.unpark(next);}}
}