package deadLock;/** * @author zhy * @create 2021/9/30 23:41 */public class Test4 { static boolean flag = true; public static void main(String[] args) { new Thread(() -> { synchronized (Test4.class) { for (int i = 0; i < 100; i += 2) { while (!flag) { try { Test4.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " : " + i); flag = false; Test4.class.notifyAll(); } } }, "t1").start(); new Thread(() -> { synchronized (Test4.class) { for (int i = 1; i < 100; i += 2) { while (flag) { try { Test4.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " : " + i); flag = true; Test4.class.notifyAll(); } } }, "t2").start(); }}
package deadLock;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * @author zhy * @create 2021/9/30 23:21 */public class Test3 { static Lock lock = new ReentrantLock(); static Condition condition1 = lock.newCondition(); static Condition condition2 = lock.newCondition(); static boolean flag = true; public static void main(String[] args) { new Thread(() -> { for (int i = 0; i < 100; i += 2) { try { lock.lock(); while (!flag){ condition1.await(); } System.out.println(Thread.currentThread().getName() + ":" + i); flag = false; condition2.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }, "t1").start(); new Thread(() -> { for (int i = 1; i < 100; i += 2) { try { lock.lock(); while (flag){ condition2.await(); } System.out.println(Thread.currentThread().getName() + ":" + i); flag = true; condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }, "t2").start(); }}