解法1:使用 wait notify
package io.github.mirrormingzz.multithreading;
import java.util.concurrent.CompletableFuture;
/**
* 两个线程交替打印 0-100
*
* @author Mireal
*/
public class TwoThreadsAlternatelyPrint {
private static int count = 0;
private static final Object LOCK = new Object();
public static void main(String[] args) {
solution1();
}
public static void solution1() {
Runnable printer = () -> {
while (count <= 100) {
synchronized (LOCK) {
System.out.println(Thread.currentThread().getName() + " -> " + count++);
LOCK.notify();
if (count <= 100) {
try {
// 让出当前的🔒
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
CompletableFuture.allOf(
CompletableFuture.runAsync(printer),
CompletableFuture.runAsync(printer)
).join();
}
}
解法2:使用 synchronized
package io.github.mirrormingzz.multithreading;
import java.util.concurrent.CompletableFuture;
/**
* 两个线程交替打印 0-100
*
* @author Mireal
*/
public class TwoThreadsAlternatelyPrint {
private static int count = 0;
private static final Object LOCK = new Object();
public static void main(String[] args) {
solution2();
}
public static void solution2() {
new Thread(() -> {
while (count < 100) {
synchronized (LOCK) {
if ((count & 1) == 0) {
System.out.println("偶数线程 -> " + count++);
}
}
}
}).start();
new Thread(() -> {
while (count < 100) {
synchronized (LOCK) {
if ((count & 1) == 1) {
System.out.println("奇数线程 -> " + count++);
}
}
}
}).start();
}
}
解法3:使用 Java8 CompletableFuture synchronized
package io.github.mirrormingzz.multithreading;
import java.util.concurrent.CompletableFuture;
/**
* 两个线程交替打印 0-100
*
* @author Mireal
*/
public class TwoThreadsAlternatelyPrint {
private static int count = 0;
private static final Object LOCK = new Object();
public static void main(String[] args) {
solution3();
}
public static void solution3() {
CompletableFuture<Void> t1 = CompletableFuture.runAsync(() -> {
while (count < 100) {
synchronized (LOCK) {
if ((count & 1) == 0) {
System.out.println("偶数线程 -> " + count++);
}
}
}
});
CompletableFuture<Void> t2 = CompletableFuture.runAsync(() -> {
while (count < 100) {
synchronized (LOCK) {
if ((count & 1) == 1) {
System.out.println("奇数线程 -> " + count++);
}
}
}
});
CompletableFuture.allOf(t1, t2).join();
}
}
源码地址:https://github.com/mirrormingzZ/JavaInterview
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。