1. package deadLock;
    2. /**
    3. * @author zhy
    4. * @create 2021/9/30 23:41
    5. */
    6. public class Test4 {
    7. static boolean flag = true;
    8. public static void main(String[] args) {
    9. new Thread(() -> {
    10. synchronized (Test4.class) {
    11. for (int i = 0; i < 100; i += 2) {
    12. while (!flag) {
    13. try {
    14. Test4.class.wait();
    15. } catch (InterruptedException e) {
    16. e.printStackTrace();
    17. }
    18. }
    19. System.out.println(Thread.currentThread().getName() + " : " + i);
    20. flag = false;
    21. Test4.class.notifyAll();
    22. }
    23. }
    24. }, "t1").start();
    25. new Thread(() -> {
    26. synchronized (Test4.class) {
    27. for (int i = 1; i < 100; i += 2) {
    28. while (flag) {
    29. try {
    30. Test4.class.wait();
    31. } catch (InterruptedException e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. System.out.println(Thread.currentThread().getName() + " : " + i);
    36. flag = true;
    37. Test4.class.notifyAll();
    38. }
    39. }
    40. }, "t2").start();
    41. }
    42. }
    1. package deadLock;
    2. import java.util.concurrent.locks.Condition;
    3. import java.util.concurrent.locks.Lock;
    4. import java.util.concurrent.locks.ReentrantLock;
    5. /**
    6. * @author zhy
    7. * @create 2021/9/30 23:21
    8. */
    9. public class Test3 {
    10. static Lock lock = new ReentrantLock();
    11. static Condition condition1 = lock.newCondition();
    12. static Condition condition2 = lock.newCondition();
    13. static boolean flag = true;
    14. public static void main(String[] args) {
    15. new Thread(() -> {
    16. for (int i = 0; i < 100; i += 2) {
    17. try {
    18. lock.lock();
    19. while (!flag){
    20. condition1.await();
    21. }
    22. System.out.println(Thread.currentThread().getName() + ":" + i);
    23. flag = false;
    24. condition2.signal();
    25. } catch (InterruptedException e) {
    26. e.printStackTrace();
    27. } finally {
    28. lock.unlock();
    29. }
    30. }
    31. }, "t1").start();
    32. new Thread(() -> {
    33. for (int i = 1; i < 100; i += 2) {
    34. try {
    35. lock.lock();
    36. while (flag){
    37. condition2.await();
    38. }
    39. System.out.println(Thread.currentThread().getName() + ":" + i);
    40. flag = true;
    41. condition1.signal();
    42. } catch (InterruptedException e) {
    43. e.printStackTrace();
    44. } finally {
    45. lock.unlock();
    46. }
    47. }
    48. }, "t2").start();
    49. }
    50. }