java多线程顺序打印ABC
import java.util.*;
//import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.LockSupport;
public class test {
static Thread threadA, threadB, threadC;
public static void main(String[] args) {
threadA = new Thread(() -> {
// for (int i = 0; i < 10; i++) {
// 打印当前线程名称
// System.out.print(Thread.currentThread().getName());
System.out.print("A");
// 唤醒下一个线程
LockSupport.unpark(threadB);
// 当前线程阻塞
LockSupport.park();
// }
});
threadB = new Thread(() -> {
// 先阻塞等待被唤醒
LockSupport.park();
System.out.print(Thread.currentThread().getName());
// 唤醒下一个线程
LockSupport.unpark(threadC);
}, "B");
threadC = new Thread(() -> {
// 先阻塞等待被唤醒
LockSupport.park();
System.out.print(Thread.currentThread().getName());
// 唤醒下一个线程
LockSupport.unpark(threadA);
}, "C");
threadA.start();
threadB.start();
threadC.start();
}
}
使用信号量交替打印ABC(打印10次)
static class Printer implements Runnable {
private char letter;
private Semaphore currentSemaphore;
private Semaphore nextSemaphore;
public Printer(char letter, Semaphore currentSemaphore, Semaphore nextSemaphore) {
this.letter = letter;
this.currentSemaphore = currentSemaphore;
this.nextSemaphore = nextSemaphore;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
// 获取当前信号量的许可
currentSemaphore.acquire();
System.out.print(letter);
// 释放下一个信号量的许可
nextSemaphore.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public static void main(String[] args) {
Thread threadA = new Thread(new Printer('A', semaphoreA, semaphoreB));
Thread threadB = new Thread(new Printer('B', semaphoreB, semaphoreC));
Thread threadC = new Thread(new Printer('C', semaphoreC, semaphoreA));
threadA.start();
threadB.start();
threadC.start();```
原文地址:https://blog.csdn.net/bigbig1984/article/details/105588949
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!