【异步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 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实现匿名的操作。

你可能感兴趣的:(#,java多线程,java)