java两线程交替打印1 0_【高频面试】两个线程交替打印0 - 100

本文介绍了三种Java实现两个线程交替打印0到100的方法:1) 使用wait和notify;2) 利用synchronized关键字;3) 结合Java 8的CompletableFuture。每种解法都通过示例代码详细阐述了实现思路。
摘要由CSDN通过智能技术生成

解法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 t1 = CompletableFuture.runAsync(() -> {

while (count < 100) {

synchronized (LOCK) {

if ((count & 1) == 0) {

System.out.println("偶数线程 -> " + count++);

}

}

}

});

CompletableFuture t2 = CompletableFuture.runAsync(() -> {

while (count < 100) {

synchronized (LOCK) {

if ((count & 1) == 1) {

System.out.println("奇数线程 -> " + count++);

}

}

}

});

CompletableFuture.allOf(t1, t2).join();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值