多线程交替顺序打印100
遇到一个面试题,三个线程交替打印至100,线程1打印1,4,7;线程二打印2,5,8;线程三打印3,6,9;当时没有想到,补上自己的实现方法mark一下
package com.study.hc.net.designPattern;
/**
* 功能描述
*
* @author Gandalf-z
* @date 2021/3/6 16:44
*/
public class MultiThreadPrint {
/**
* 线程交替执行控制器
*/
private static int thread_index = 0;
/**
* 执行打印计数器,用于判断循环退出条件,需要加volatile,保证可见性
*/
private static volatile int count = 0;
/**
* 线程争抢的锁对象,持有该对象的锁方可执行操作
*/
private static Object obj = new Object();
public static void main(String[] args) {
new Thread(() -> {
printByOrder(0);
}, "Thread-1").start();
new Thread(() -> {
printByOrder(1);
}, "Thread-2").start();
new Thread(() -> {
printByOrder(2);
}, "Thread-3").start();
}
/**
* 顺序打印100
*
* @param i 线程序号
*/
public static void printByOrder(int i) {
while (count < 100) {
if (thread_index % 3 == i) {
synchronized (obj) {
count++;
thread_index++;
System.out.println(Thread.currentThread().getName() + ":" + count);
}
}
}
}
}
执行结果
使用Semaphore实现
import java.util.concurrent.Semaphore;
/**
* 功能描述 基于Semaphore实现顺序打印
*
* @author Gandalf-z
* @date 2021/3/6 20:02
*/
public class MultiPrintSemaphore {
public static Semaphore semaphore = new Semaphore(1);
public static volatile int count = 0;
public static int index = 0;
public static void main(String[] args) {
new Thread(() -> {
printOrderBySemaphore(0);
}, "Thread-1").start();
new Thread(() -> {
printOrderBySemaphore(1);
}, "Thread-2").start();
new Thread(() -> {
printOrderBySemaphore(2);
}, "Thread-3").start();
}
private static void printOrderBySemaphore(int i) {
while (count < 100) {
if (index % 3 == i) {
try {
semaphore.acquire();
count++;
index++;
System.out.println(Thread.currentThread().getName() + ":" + count);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
执行结果
路漫漫其修远兮,吾将上下而求索