ABC三个线程顺序执行(简单实现)

需求:3个线程 输出ABC ------> ABCABCABC。。。。。此类型
ps:2020-12-19 更新了6种

 

1、 使用线程池 将所有线程放入一个队列 ,保证顺序输出

public class ThreeThread {
    
    public static void main(String[] args) throws InterruptedException {

        //用线程池来实现 ,3个线程加入线程池
        ExecutorService pool = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            pool.submit(()-> System.out.println("A"));
            pool.submit(()-> System.out.println("B"));
            pool.submit(()-> System.out.println("C"));
        }
        pool.shutdown();

    }

}

2、java.util.concurrent.atomic.AtomicInteger 保证原子操作

/**.
 * Created by: yuqiang
 * Date: 2020/12/18 10:54
 * Description: java.util.concurrent.atomic.AtomicInteger 控制
 */
public class Foo {

  private AtomicInteger flag = new AtomicInteger(1);

  public Foo() { }

  public void first(String str) throws InterruptedException {
    while(flag.get()%3 != 1){    };
    System.out.println(str);
    flag.incrementAndGet();
  }

  public void second(String str) throws InterruptedException {
    while(flag.get()%3 != 2){    };
    System.out.println(str);
    flag.incrementAndGet();

  }

  public void third(String str) throws InterruptedException {
    while(flag.get()%3 != 0){    };
    System.out.println(str);
    flag.incrementAndGet();
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();
    new Thread(()->{
      try {
        for (int i = 0; i < 3; i++) {
          Thread.sleep(100);
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 3; i++) {
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 3; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

  }
  
}

3、volatile 控制flag在并发环境中可见

/**.
 * Created by:yuqiang
 * Date: 2020/12/18 10:54
 * Description: volatile 控制flag在并发环境中可见
 */
public class Foo {

  private volatile int flag = 1;

  public Foo() {

  }

  public void first(String str) throws InterruptedException {
    while(flag%3 != 1){
    };
    System.out.println(str);
    flag++;
  }

  public void second(String str) throws InterruptedException {
    while(flag%3 != 2){
    };
    System.out.println(str);
    flag++;

  }

  public void third(String str) throws InterruptedException {
    while(flag%3 != 0){
    };
    System.out.println(str);
    System.out.println("==============");
    flag++;
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(500);
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();



    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

  }

}

4、synchronized  wait() notifyAll() 控制

/**
 * Created by: e-yuqiang1
 * Date: 2020/12/18 10:54
 * Description: synchronized  wait() notifyAll()
 */
public class Foo {

  private int flag = 1;

  public Foo() {

  }

  public synchronized void first(String str) throws InterruptedException {
    while(flag%3 != 1){
      wait();
    };
    System.out.println(str);
    flag++;
    notifyAll();
  }

  public synchronized void second(String str) throws InterruptedException {
    while(flag%3 != 2){
      wait();
    };
    System.out.println(str);
    flag++;
    notifyAll();
  }

  public synchronized void third(String str) throws InterruptedException {
    while(flag%3 != 0){
      wait();
    };
    System.out.println(str);
    System.out.println("=====================");
    flag++;
    notifyAll();
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(500);
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
  }
  
}

5、LockReentrantLock Condition(await(),signalAll()) 控制

/**
 * Created by: e-yuqiang1
 * Date: 2020/12/18 10:54
 * Description:
 */
public class Foo {

  private int flag = 1;

  private Lock lock;
  private Condition condition;

  public Foo() {
    lock = new ReentrantLock();
    condition = lock.newCondition();
  }

  public void first(String str) throws InterruptedException {
    lock.lock();
    try {
      while(flag%3 != 1){
        condition.await();
      }
      System.out.println(str);
      flag++;
      condition.signalAll();
    } finally {
      lock.unlock();
    }

  }

  public void second(String str) throws InterruptedException {
    lock.lock();
    try {
      while(flag%3 != 2){
        condition.await();
      }
    System.out.println(str);
    flag++;
    condition.signalAll();
    } finally {
      lock.unlock();
    }
  }

  public void third(String str) throws InterruptedException {
    lock.lock();
    try {
      while(flag%3 != 0){
        condition.await();
      }
    System.out.println(str);
    System.out.println("=====================");
    flag++;
    condition.signalAll();
  } finally {
    lock.unlock();
  }
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(500);
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
  }

}

6、信号量 semaphore(.acquire() .release())

/**
 * Created by: e-yuqiang1
 * Date: 2020/12/18 10:54
 * Description:
 */
public class Foo {


  private Semaphore semaphoreA;
  private Semaphore semaphoreB;
  private Semaphore semaphoreC;

  public Foo() throws InterruptedException {
    semaphoreA = new Semaphore(1);
    semaphoreB = new Semaphore(1);
    semaphoreC = new Semaphore(1);
    semaphoreB.acquire();//提前请求B
    semaphoreC.acquire();//提前请求C
  }

  public void first(String str) throws InterruptedException {
    semaphoreA.acquire();
    System.out.println(str);
    semaphoreB.release();
  }

  public void second(String str) throws InterruptedException {
    semaphoreB.acquire();
    System.out.println(str);
    semaphoreC.release();
  }

  public void third(String str) throws InterruptedException {
    semaphoreC.acquire();
    System.out.println(str);
    System.out.println("=====================");
    semaphoreA.release();
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(1000);
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
  }

}

7、CountDownLatch(.await() .countDown())  计数器(减法) 

  ps:感觉比较取巧 不推荐这种写法

/**
 * Created by: e-yuqiang1
 * Date: 2020/12/18 10:54
 * Description: 写的挺Low的 试了半个小时
 */
public class Foo {


  private CountDownLatch countDownLatchA;
  private CountDownLatch countDownLatchB;
  private CountDownLatch countDownLatchC;

  public Foo() throws InterruptedException {
    countDownLatchA = new CountDownLatch(1);
    countDownLatchB = new CountDownLatch(1);
    countDownLatchC = new CountDownLatch(1);
    countDownLatchA.countDown();
  }

  public void first(String str) throws InterruptedException {
    countDownLatchA.await();
    System.out.println(str);
    countDownLatchA= new CountDownLatch(1);
    countDownLatchB.countDown();
  }

  public void second(String str) throws InterruptedException {
    countDownLatchB.await();
    System.out.println(str);
    countDownLatchB = new CountDownLatch(1);
    countDownLatchC.countDown();
  }

  public void third(String str) throws InterruptedException {
    countDownLatchC.await();
    System.out.println(str);
    System.out.println("=====================");
    countDownLatchC = new CountDownLatch(1);
    countDownLatchA.countDown();
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
  }

}

8、BlockingQueue(.take() .put()) 阻塞队列控制

/**
 * Created by: e-yuqiang1
 * Date: 2020/12/18 10:54
 * Description: BlockingQueue 阻塞队列
 */
public class Foo {


  private BlockingQueue<Integer> blockingQueueA;
  private BlockingQueue<Integer> blockingQueueB;
  private BlockingQueue<Integer> blockingQueueC;


  public Foo() throws InterruptedException {
    blockingQueueA = new ArrayBlockingQueue<>(1);
    blockingQueueB = new ArrayBlockingQueue<>(1);
    blockingQueueC = new ArrayBlockingQueue<>(1);
    blockingQueueA.put(1);
  }

  public void first(String str) throws InterruptedException {
    blockingQueueA.take();
    System.out.println(str);
    blockingQueueB.put(2);
  }

  public void second(String str) throws InterruptedException {
    blockingQueueB.take();
    System.out.println(str);
    blockingQueueC.put(3);
  }

  public void third(String str) throws InterruptedException {
    blockingQueueC.take();
    System.out.println(str);
    System.out.println("=====================");
    blockingQueueA.put(1);
  }

  public static void main(String[] args) throws InterruptedException {
    Foo foo = new Foo();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(500);
          foo.second("B");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(300);
          foo.first("A");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();

    new Thread(()->{
      try {
        for (int i = 0; i < 10; i++) {
          foo.third("C");
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
  }

}

目前想到了只有这8种......

 

 

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用Java中的多线程机制来实现三个线程顺序打印ABC。以下是一种可能的实现方式: ```java public class PrintABC { private static final Object lock = new Object(); // 共享锁对象 private static volatile int state = 0; // 当前打印状态,0表示打印A,1表示打印B,2表示打印C public static void main(String[] args) { Thread threadA = new Thread(new PrintThread("A", 0)); Thread threadB = new Thread(new PrintThread("B", 1)); Thread threadC = new Thread(new PrintThread("C", 2)); threadA.start(); threadB.start(); threadC.start(); } static class PrintThread implements Runnable { private String name; private int targetState; public PrintThread(String name, int targetState) { this.name = name; this.targetState = targetState; } @Override public void run() { for (int i = 0; i < 10; i++) { // 打印10次 synchronized (lock) { while (state != targetState) { // 当前状态不是目标状态,等待 try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(name); // 打印字符 state = (state + 1) % 3; // 更新状态 lock.notifyAll(); // 唤醒其他线程 } } } } } ``` 在上述代码中,我们创建了一个共享的锁对象 `lock` 和一个共享的状态变量 `state`。每个线程在运行时,都会先检查当前的状态是否为目标状态,如果不是则等待,直到状态匹配后打印对应的字符,并更新状态,然后唤醒其他线程。 通过 `Thread.currentThread().getName()` 可以获取当前线程的名字。 以上代码是一种简单实现方式,但是由于多线程执行是不确定的,所以打印的结果可能会交错。若要确保按照顺序打印ABC,可以使用信号量(Semaphore)等更高级的同步机制。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值