public class Test { public static volatile int flag = 0; public static void main(String[] args) { new Thread(new Runnable1()).start(); new Thread(new Runnable2()).start(); }}class Runnable1 implements Runnable { @Override public void run() { int i = 1; while (i < 100) { if (Test.flag == 0) { System.out.println("线程1:" + i); i += 2; Test.flag = 1; } } }}class Runnable2 implements Runnable { @Override public void run() { int i = 2; while (i <= 100) { if (Test.flag == 1) { System.out.println("线程2:" + i); i += 2; Test.flag = 0; } } }}
public class Test { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); new Thread(myRunnable, "线程1").start(); new Thread(myRunnable, "线程2").start(); }}class MyRunnable implements Runnable { private int i = 1; @SneakyThrows @Override public void run() { while (i <= 100) { synchronized (this) { System.out.println(Thread.currentThread().getName() + ":" + i++); notify(); if (i <= 100) { wait(); } } } }}
public class Test { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); new Thread(myRunnable, "线程1").start(); new Thread(myRunnable, "线程2").start(); }}class MyRunnable implements Runnable { private int i = 1; private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); @Override public void run() { while (i <= 100) { lock.lock(); System.out.println(Thread.currentThread().getName() + ":" + i++); condition.signal(); try { if (i <= 100) { condition.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }}