
多线程交替打印:A B C 循环
这是一个多线程任务中的:依次执行问题
方式一:LockSupport
package com.chstack.learning.concurrent.abc;
import java.util.concurrent.locks.LockSupport;
public class LockSuppABC {
static Thread threadA, threadB, threadC;
public static void print(String str, Thread next) {
for (int i = 0; i < 3; i++) { // 打印100次
LockSupport.park(); // 当前线程阻塞
System.out.print(str);
LockSupport.unpark(next); // 唤醒下一个线程
}
}
public static void main(String[] args) {
threadA = new Thread(() -> print("A\n", threadB));
threadB = new Thread(() -> print("B\n", threadC));
threadC = new Thread(() -> print("C\n", threadA));
threadA.start();
threadB.start();
threadC.start();
// 触发第一个线程(A)
LockSupport.unpark(threadA);
}
}方式二:Semaphore
package com.chstack.learning.concurrent.abc;
import java.util.concurrent.Semaphore;
public class SemaphoreABC {
public static void main(String[] args) {
Semaphore semaphoreA = new Semaphore(1);
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(0);
int times = 3;
new Thread(()->{
for (int i = 0; i < times; i++) {
try {
semaphoreA.acquire();
System.out.println("A");
semaphoreB.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
new Thread(()->{
for (int i = 0; i < times; i++) {
try {
semaphoreB.acquire();
System.out.println("B");
semaphoreC.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
new Thread(()->{
for (int i = 0; i < times; i++) {
try {
semaphoreC.acquire();
System.out.println("C");
semaphoreA.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
}
}