Package test1;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock; /** * Write a program to open 3 threads, * These 3 thread IDs are a, B, C, * each thread prints its own ID on the screen 10 times, * requires the output to be displayed in the order of ABC; * For example: abcabc .... recursive * * Design: lock+
Condition (can interpret a, B, C as the main thread, sub-thread, grandchild thread) * @author Mahone * * */public class Test3 {public static void main (string[] args) {
Test3 obj = new Test3 ();
Obj.init ();
} private void Init () {final test3business TB = new test3business (); Thread t1 = new Thread (new Runnable () {@Override public void run () {for (int i = 0; i <; i++) {TB.
PrintA ();
}
}
});
T1.setname ("A"); Thread t2 = new Thread (new Runnable () {@Override public void run () {for (int i = 0; i <; i++) {TB.
PRINTB ();
}
}
});
T2.setname ("B"); Thread t3 = new Thread (new Runnable () {@Override public void run () {for (int i = 0; i <; i++) {TB.
PRINTC ();}
}
});
T3.setname ("C");
T1.start ();
T2.start ();
T3.start ();
}} class Test3business {private String flag = "A";
Private lock lock = new Reentrantlock ();
Private Condition CA = Lock.newcondition ();
Private Condition CB = Lock.newcondition ();
Private Condition CC = Lock.newcondition ();
public void PrintA () {try {lock.lock ();
if (!flag.equals ("A")) {ca.await ();
} System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (1000);
Flag = "B";
Cb.signal ();
} catch (Exception ex) {ex.printstacktrace ();
}finally {lock.unlock ();
}} public void Printb () {try {lock.lock ();
if (!flag.equals ("B")) {cb.await ();
} System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (1000);
Flag = "C";
Cc.signal ();
} catch (Exception ex) {ex.printstacktrace ();
}finally {lock.unlock ();
}} public void Printc () {try {lock.lock ();
if (!flag.equals ("C")) { Cc.await ();
} System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (1000);
Flag = "A";
Ca.signal ();
} catch (Exception ex) {ex.printstacktrace ();
}finally {lock.unlock ();
}
}
}