【异步IO】 1.AtomicReference持有对象 2.解决跨线程对象传递问题 3.使用FunctionInterface实现匿名函数 4.体会IO线程和逻辑线程的通信

 Main.java

package org.example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class Main {
    /*** 逻辑线程 */
    static public ExecutorService logicThread = Executors.newSingleThreadExecutor();

    /*** IO线程 */
    static public ExecutorService[] ioThreadArray = new ExecutorService[Runtime.getRuntime().availableProcessors()];

    /*** 初始化 */
    static {
        for (int i = 0; i < ioThreadArray.length; i++) {
            ioThreadArray[i] = Executors.newSingleThreadExecutor();
        }
    }

    static public void main(String[] args) {
        // 在这里设置想要的任何结果类型
        AtomicReference<Integer> num = new AtomicReference<>();

        asyncProcess(
                // 线程绑定参数
                123,
                
                // 通过FunctionInterface实现匿名函数
                // 这个是等待在IO线程的操作实现,比如:DB操作,里面是IO线程
                () -> {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    // 最终计算拿到结果,使用AtomicReference设置过去
                    num.set(12345);
                },
                
                // 拿到AtomicReference设置的值
                // 这个方法体内,是再次回到了逻辑线程了
                () -> {
                    Integer ret = num.get();
                    System.out.println("ret=" + ret + " " + Thread.currentThread().getName());
                }
        );
    }

    /**
     * 封装异步操作
     *
     * @param hashId
     * @param async
     * @param finish
     */
    static public void asyncProcess(Object hashId, IDoAsync async, IDoFinish finish) {
        int index = Math.abs(hashId.hashCode() % ioThreadArray.length);
        ioThreadArray[index].submit(() -> {
            // 在IO线程中执行耗时操作
            safeRun(async::doAsync);

            // 将最终结果提交到业务线程
            // 这里其实就是线程间通信: 扔一个消息过去嘛!!!
            logicThread.submit(() -> safeRun(finish::doFinish));
        });
    }

    static void safeRun(Runnable run) {
        try {
            run.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

IDoAsync.java // 异步操作的封装

package org.example;

@FunctionalInterface
public interface IDoAsync {
    void doAsync();
}

IDoFinish.java // 完成后的回调

package org.example;

@FunctionalInterface
public interface IDoFinish {
    void doFinish();
}

总结:

1.通过FunctionInterface实现匿名的操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的`java.util.concurrent.atomic.AtomicReference`提供了一种线程安全的方式来更新对象引用。它通过使用CAS(Compare-And-Swap)算法实现了原子性的操作。 下面是一个简单的案例,展示如何使用`AtomicReference`类: ```java import java.util.concurrent.atomic.AtomicReference; public class AtomicReferenceExample { public static void main(String[] args) { // 初始化AtomicReference对象 AtomicReference<String> atomicReference = new AtomicReference<>("Hello"); // 获取当前对象引用的值 String currentValue = atomicReference.get(); System.out.println("Current value: " + currentValue); // 比较并替换 boolean updated = atomicReference.compareAndSet("Hello", "World"); System.out.println("Value updated: " + updated); // 获取更新后的值 String updatedValue = atomicReference.get(); System.out.println("Updated value: " + updatedValue); } } ``` 在上面的示例中,我们首先创建了一个`AtomicReference`对象,并初始化为字符串`"Hello"`。然后我们使用`compareAndSet`方法比较当前对象引用的值是否为`"Hello"`,如果是,则将其替换为`"World"`。最后,我们获取更新后的值,并输出到控制台。 需要注意的是,`AtomicReference`类提供了许多其他有用的方法,如`set`、`getAndSet`、`weakCompareAndSet`等,可以根据具体的需求选择使用。 总之,`AtomicReference`类是Java中一种非常有用的线程安全对象引用类,可以避免多个线程同时修改对象引用时出现的竞争条件问题

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值