多執行緒順序列印ABC
阿新 • • 發佈:2020-08-02
import java.util.concurrent.locks.ReentrantLock; public class AsynObject { private volatile int count; private ReentrantLock lock = new ReentrantLock(); public AsynObject(int count) { this.count = count; } public void printA() { print("A", 0); } publicvoid printB() { print("B", 1); } public void printC() { print("C", 2); } private void print(String name, int a) { lock.lock(); try { if (count % 3 == a) { System.out.println(name); count++; Thread.sleep(100); } } catch (Exception ex) { } finally { lock.unlock(); } } }
public static void main(String[] args) { AsynObject asynObject = new AsynObject(3); Thread printThreadA = new Thread(() -> { while (true){ asynObject.printA(); } }); printThreadA.start(); Thread printThreadB= new Thread(() -> { while (true){ asynObject.printB(); } }); printThreadB.start(); Thread printThreadC = new Thread(() -> { while (true){ asynObject.printC(); } }); printThreadC.start(); }