欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java多线程实现有序输出ABC

程序员文章站 2023-10-30 18:11:46
3个线程,线程1输出a,线程2输出b,线程3输出c,让这个3个线程循环有序地输出abcabc… 看到这个题目,感觉很有意思,问题的本质是在多线程执行环境,控制线程的执行顺...

3个线程,线程1输出a,线程2输出b,线程3输出c,让这个3个线程循环有序地输出abcabc…

看到这个题目,感觉很有意思,问题的本质是在多线程执行环境,控制线程的执行顺序,实现的方式有非常多种,本质上需要解决java多线程环境下的线程执行的同步和利用锁机制来控制线程的执行顺序。

方式1:利用synchronized

这种方式也就是使用java内置的monitor机制,配合wait和notifyall,代码如下:

(1)利用volatile做线程间资源的同步访问,同时作为线程调度的标志;
(2)利用notifyall来唤醒其他等待当前的monitor资源的线程;

public class threadorderwithsync {

  private volatile int flag = 'a';
  private final static object lock = new object();

  runnable a = () -> {
    while (true) {
      synchronized (lock) {
        if (flag == 'a' ) {
          system.out.println("a");

          flag = 'b';
          // let other thread race to get the monitor
          lock.notifyall();
        } else {
          try {
            lock.wait();
          } catch (interruptedexception e) {
            e.printstacktrace();
          }
        }
      }
    }
  };

  runnable b = () -> {
    while (true) {
      synchronized (lock) {
        if (flag == 'b' ) {
          system.out.println("b");

          flag = 'c';
          // let other thread race to get the monitor
          lock.notifyall();
        } else {
          try {
            lock.wait();
          } catch (interruptedexception e) {
            e.printstacktrace();
          }
        }
      }
    }
  };

  runnable c = () -> {
    while (true) {
      synchronized (lock) {
        if (flag == 'c' ) {
          system.out.println("c");

          flag = 'a';
          // let other thread race to get the monitor
          lock.notifyall();
        } else {
          try {
            lock.wait();
          } catch (interruptedexception e) {
            e.printstacktrace();
          }
        }
      }
    }
  };

  public void runtest() {
    thread ta = new thread(a);
    thread tb = new thread(b);
    thread tc = new thread(c);

    ta.start();
    tb.start();
    tc.start();
  }

  public static void main(string[] args) {
    threadorderwithsync sync = new threadorderwithsync();
    sync.runtest();
  }
}

方式2:利用并发包reentrantlock和condition的锁机制

上面方式1的synchronized机制,因为当前的所有线程都争用同一个monitor资源,因此只能通过notifyall来通知其他线程来加锁,因此每次都会出现race condition,但是,通过reentrantlock的condition,我们可以精确控制,下一个该唤醒signal的线程是哪一个(因为我们知道执行的顺序是a->b->c的循环),相比synchronized的机制,condition机制可以更精细化线程的调度设计,代码示例如下:

/**
 * @author xijin.zeng created on 2018/8/31
 * thrads runing order: a->b->c
 */
public class threadorderwithcondition {

  private static final reentrantlock lock = new reentrantlock();
  private static final condition c_a = lock.newcondition();
  private static final condition c_b = lock.newcondition();
  private static final condition c_c = lock.newcondition();

  /**
   * init for a to run first
   */
  private volatile int flag = 'a';

  runnable a = () -> {
    while (true) {
      lock.lock();

      if (flag == 'a') {
        system.out.println("a");
        flag = 'b';
        // signal b to run
        c_b.signal();
      } else {
        try {
          // block and wait signal to invoke
          c_a.await();
        } catch (interruptedexception e) {
          e.printstacktrace();
        }
      }

      lock.unlock();
    }
  };

  runnable b = () -> {
    while (true) {
      lock.lock();

      if (flag == 'b') {
        system.out.println("b");
        flag = 'c';
        // signal c to run
        c_c.signal();
      } else {
        try {
          // block and wait signal to invoke
          c_b.await();
        } catch (interruptedexception e) {
          e.printstacktrace();
        }
      }

      lock.unlock();
    }
  };

  runnable c = () -> {
    while (true) {
      lock.lock();

      if (flag == 'c') {
        system.out.println("c");
        flag = 'a';
        // signal a to run
        c_a.signal();
      } else {
        try {
          // block and wait signal to invoke
          c_c.await();
        } catch (interruptedexception e) {
          e.printstacktrace();
        }
      }

      lock.unlock();
    }
  };

  public void runtest() {
    thread threada = new thread(a);
    thread threadb = new thread(b);
    thread threadc = new thread(c);

    threada.start();
    threadb.start();
    threadc.start();
  }

  public static void main(string[] args) {
    threadorderwithcondition o = new threadorderwithcondition();
    o.runtest();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。