要求创建3个线程,分别打印ABC,共交替打印10次。
public class Main {
private static Semaphore A = new Semaphore(1);
private static Semaphore B = new Semaphore(0);
private static Semaphore C = new Semaphore(0);
public static void main(String[] args) {
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
A.acquire();
System.out.print("A");
B.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
B.acquire();
System.out.print("B");
C.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
C.acquire();
System.out.print("C");
A.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
控制台输出:
ABCABCABCABCABCABCABCABCABCABC
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)