三个线程交替打印输出
public class AlternateOutput {
public static void main(String[] args) {
// Test1 test1 = new Test1();
// new Thread(()->{
// try {
// test1.print(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }).start();
// new Thread(()->{
// try {
// test1.print(2);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }).start();
// new Thread(()->{
// try {
// test1.print(3);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }).start();
// Test2 test2 = new Test2();
// Thread t1 = new Thread(()->{
// try {
// test2.print("a");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// });
// Thread t2 = new Thread(()->{
// try {
// test2.print("b");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// });
// Thread t3 = new Thread(()->{
// try {
// test2.print("c");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// });
// test2.setThreads(t1,t2,t3);
// test2.start();
Test3 test3 = new Test3();
Condition condition1 = test3.newCondition();
Condition condition2 = test3.newCondition();
Condition condition3 = test3.newCondition();
new Thread(()->{
test3.print("a",condition1,condition2);
}).start();
new Thread(()->{
test3.print("b",condition2,condition3);
}).start();
new Thread(()->{
test3.print("c",condition3,condition1);
}).start();
test3.start(condition1);
}
}
class Test1{
private Integer flag = 1;
private Integer num = 10;
public void print(int curFlag) throws InterruptedException {
for (int i=0; i<num; ++i){
synchronized (this){
while (this.flag != curFlag){
this.wait();
}
System.out.println(curFlag);
this.flag = curFlag % 3 + 1;
this.notifyAll();
}
}
}
}
class Test2{
private Thread[] threads;
private Integer num = 10;
public Test2(Thread... threads) {
this.threads = threads;
}
public void setThreads(Thread... threads) {
this.threads = threads;
}
public void print(String s) throws InterruptedException {
for (int i=0;i<num;++i){
LockSupport.park();
System.out.println(s);
LockSupport.unpark(getNextThread());
}
}
public Thread getNextThread(){
int size = threads.length;
Thread cur = Thread.currentThread();
for (int i=0;i<size;++i){
if (cur == threads[i]){
return threads[(i + 1) % size];
}
}
return null;
}
public void start() {
for (Thread thread: threads){
thread.start();
}
LockSupport.unpark(threads[0]);
}
}
class Test3 extends ReentrantLock{
private int num = 10;
public void start(Condition condition){
this.lock();
try {
condition.signal();
}finally {
this.unlock();
}
}
public void print(String s, Condition cur,Condition next){
for (int i=0;i<num;++i){
this.lock();
try{
cur.await();
System.out.println(s);
next.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
this.unlock();
}
}
}
}