Advertisement
the_alator

Java threads 18+

May 21st, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. package features;
  2.  
  3. public class ThreadLadder {
  4. static Object a1 = new Object();
  5. static Object a2 = new Object();
  6. static Object a3 = new Object();
  7. static Object a4 = new Object();
  8. static Object a5 = new Object();
  9.  
  10. public static void main(String[] args) throws InterruptedException {
  11. new Thread(ThreadLadder::syncLadder, "1").start();
  12. Thread.sleep(500);
  13. new Thread(ThreadLadder::reverseSyncLadder, "2").start();
  14. }
  15.  
  16. public static void syncLadder() {
  17. try {
  18. synchronized(a1) {
  19. System.out.println(Thread.currentThread().getName() + ": a1");
  20. synchronized(a2) {
  21. System.out.println(Thread.currentThread().getName() + ": a2");
  22. synchronized(a3) {
  23. System.out.println(Thread.currentThread().getName() + ": a3");
  24. synchronized(a4) {
  25. System.out.println(Thread.currentThread().getName() + ": a4");
  26. synchronized(a5) {
  27. System.out.println(Thread.currentThread().getName() + ": a5");
  28. Thread.sleep(2000);
  29. System.out.println(Thread.currentThread().getName() + ": a5");
  30. }
  31. System.out.println(Thread.currentThread().getName() + ": a4");
  32. Thread.sleep(100);
  33. }
  34. System.out.println(Thread.currentThread().getName() + ": a3");
  35. Thread.sleep(100);
  36. }
  37. System.out.println(Thread.currentThread().getName() + ": a2");
  38. Thread.sleep(100);
  39. }
  40. System.out.println(Thread.currentThread().getName() + ": a1");
  41. Thread.sleep(100);
  42. }
  43. } catch (InterruptedException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. public static void reverseSyncLadder() {
  48. synchronized(a5) {
  49. System.out.println(Thread.currentThread().getName() + ": a5");
  50. synchronized(a4) {
  51. System.out.println(Thread.currentThread().getName() + ": a4");
  52. synchronized(a3) {
  53. System.out.println(Thread.currentThread().getName() + ": a3");
  54. synchronized(a2) {
  55. System.out.println(Thread.currentThread().getName() + ": a2");
  56. synchronized(a1) {
  57. System.out.println(Thread.currentThread().getName() + ": a1");
  58. try {
  59. Thread.sleep(2000);
  60. } catch (InterruptedException e) {
  61. e.printStackTrace();
  62. }
  63. System.out.println(Thread.currentThread().getName() + ": a1");
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement