1. public class Test {
    2. public static volatile int flag = 0;
    3. public static void main(String[] args) {
    4. new Thread(new Runnable1()).start();
    5. new Thread(new Runnable2()).start();
    6. }
    7. }
    8. class Runnable1 implements Runnable {
    9. @Override
    10. public void run() {
    11. int i = 1;
    12. while (i < 100) {
    13. if (Test.flag == 0) {
    14. System.out.println("线程1:" + i);
    15. i += 2;
    16. Test.flag = 1;
    17. }
    18. }
    19. }
    20. }
    21. class Runnable2 implements Runnable {
    22. @Override
    23. public void run() {
    24. int i = 2;
    25. while (i <= 100) {
    26. if (Test.flag == 1) {
    27. System.out.println("线程2:" + i);
    28. i += 2;
    29. Test.flag = 0;
    30. }
    31. }
    32. }
    33. }
    1. public class Test {
    2. public static void main(String[] args) {
    3. MyRunnable myRunnable = new MyRunnable();
    4. new Thread(myRunnable, "线程1").start();
    5. new Thread(myRunnable, "线程2").start();
    6. }
    7. }
    8. class MyRunnable implements Runnable {
    9. private int i = 1;
    10. @SneakyThrows
    11. @Override
    12. public void run() {
    13. while (i <= 100) {
    14. synchronized (this) {
    15. System.out.println(Thread.currentThread().getName() + ":" + i++);
    16. notify();
    17. if (i <= 100) {
    18. wait();
    19. }
    20. }
    21. }
    22. }
    23. }
    1. public class Test {
    2. public static void main(String[] args) {
    3. MyRunnable myRunnable = new MyRunnable();
    4. new Thread(myRunnable, "线程1").start();
    5. new Thread(myRunnable, "线程2").start();
    6. }
    7. }
    8. class MyRunnable implements Runnable {
    9. private int i = 1;
    10. private ReentrantLock lock = new ReentrantLock();
    11. private Condition condition = lock.newCondition();
    12. @Override
    13. public void run() {
    14. while (i <= 100) {
    15. lock.lock();
    16. System.out.println(Thread.currentThread().getName() + ":" + i++);
    17. condition.signal();
    18. try {
    19. if (i <= 100) {
    20. condition.await();
    21. }
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. } finally {
    25. lock.unlock();
    26. }
    27. }
    28. }
    29. }