多線程交替順序打印100
遇到一個(gè)面試題涯呻,三個(gè)線程交替打印至100,線程1打印1,4,7;線程二打印2,5,8;線程三打印3,6,9腻要;當(dāng)時(shí)沒(méi)有想到复罐,補(bǔ)上自己的實(shí)現(xiàn)方法mark一下
package com.study.hc.net.designPattern;
/**
* 功能描述
*
* @author Gandalf-z
* @date 2021/3/6 16:44
*/
public class MultiThreadPrint {
/**
* 線程交替執(zhí)行控制器
*/
private static int thread_index = 0;
/**
* 執(zhí)行打印計(jì)數(shù)器,用于判斷循環(huán)退出條件雄家,需要加volatile效诅,保證可見(jiàn)性
*/
private static volatile int count = 0;
/**
* 線程爭(zhēng)搶的鎖對(duì)象,持有該對(duì)象的鎖方可執(zhí)行操作
*/
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 線程序號(hào)
*/
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);
}
}
}
}
}
執(zhí)行結(jié)果
使用Semaphore實(shí)現(xiàn)
import java.util.concurrent.Semaphore;
/**
* 功能描述 基于Semaphore實(shí)現(xiàn)順序打印
*
* @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();
}
}
}
}
}
執(zhí)行結(jié)果
路漫漫其修遠(yuǎn)兮趟济,吾將上下而求索