Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package features;
- public class ThreadLadder {
- static Object a1 = new Object();
- static Object a2 = new Object();
- static Object a3 = new Object();
- static Object a4 = new Object();
- static Object a5 = new Object();
- public static void main(String[] args) throws InterruptedException {
- new Thread(ThreadLadder::syncLadder, "1").start();
- Thread.sleep(500);
- new Thread(ThreadLadder::reverseSyncLadder, "2").start();
- }
- public static void syncLadder() {
- try {
- synchronized(a1) {
- System.out.println(Thread.currentThread().getName() + ": a1");
- synchronized(a2) {
- System.out.println(Thread.currentThread().getName() + ": a2");
- synchronized(a3) {
- System.out.println(Thread.currentThread().getName() + ": a3");
- synchronized(a4) {
- System.out.println(Thread.currentThread().getName() + ": a4");
- synchronized(a5) {
- System.out.println(Thread.currentThread().getName() + ": a5");
- Thread.sleep(2000);
- System.out.println(Thread.currentThread().getName() + ": a5");
- }
- System.out.println(Thread.currentThread().getName() + ": a4");
- Thread.sleep(100);
- }
- System.out.println(Thread.currentThread().getName() + ": a3");
- Thread.sleep(100);
- }
- System.out.println(Thread.currentThread().getName() + ": a2");
- Thread.sleep(100);
- }
- System.out.println(Thread.currentThread().getName() + ": a1");
- Thread.sleep(100);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public static void reverseSyncLadder() {
- synchronized(a5) {
- System.out.println(Thread.currentThread().getName() + ": a5");
- synchronized(a4) {
- System.out.println(Thread.currentThread().getName() + ": a4");
- synchronized(a3) {
- System.out.println(Thread.currentThread().getName() + ": a3");
- synchronized(a2) {
- System.out.println(Thread.currentThread().getName() + ": a2");
- synchronized(a1) {
- System.out.println(Thread.currentThread().getName() + ": a1");
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(Thread.currentThread().getName() + ": a1");
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement