Java中的异步和非阻塞操作有什么区别?

目录

1. 同步和异步的区别

2. 阻塞和非阻塞的区别


1. 同步和异步的区别

同步:同步是指任务按顺序执行,执行完一个任务后在执行下一个任务,不能同时执行。

import java.io.FileInputStream;
import java.io.IOException;

public class SynchronousExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("test.txt")) {
            System.out.println("开始读取文件...");
            int data;
            while ((data = fis.read()) != -1) { // 同步阻塞读取
                System.out.print((char) data);
            }
            System.out.println("\n文件读取完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

异步:任务可以同时进行,不需要等待前一个任务执行完成。

public static void main(String[] args) {
        System.out.println("主线程开始执行...");
        // 创建异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            System.out.println("执行异步任务...");
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            return "发送成功!";
        });
        System.out.println("主线程执行其他任务");
        //获取异步任务的结果
        try{
            String result = future.get();
            System.out.println("异步任务执行结果:"+result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

在Java中,同步可以像普通的函数的调用,而异步可能需要使用Future或者CompletableFuture来处理。

2. 阻塞和非阻塞的区别

阻塞:阻塞是指调用一个操作时,当前线程会被挂起,直到操作完成。

public class BlockingExample {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器启动,等待客户端连接...");

        Socket socket = serverSocket.accept(); // 阻塞直到客户端连接
        System.out.println("客户端已连接!");

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message = reader.readLine(); // 阻塞直到读取到数据
        System.out.println("收到客户端消息: " + message);

        socket.close();
        serverSocket.close();
    }
}

非阻塞:调用后立即返回,线程可以继续做其他事情。

public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false); // 设置为非阻塞模式
        System.out.println("服务器启动,等待客户端连接...");

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept(); // 非阻塞,立即返回
            if (socketChannel != null) {
                System.out.println("客户端已连接!");

                ByteBuffer buffer = ByteBuffer.allocate(1024);
                socketChannel.read(buffer); // 非阻塞读取
                buffer.flip();
                String message = StandardCharsets.UTF_8.decode(buffer).toString();
                System.out.println("收到客户端消息: " + message);

                socketChannel.close();
                break;
            } else {
                System.out.println("等待客户端连接中...");
                Thread.sleep(1000); // 模拟其他任务
            }
        }

        serverSocketChannel.close();
    }

异步和非阻塞的区别:异步更侧重于任务的处理方式(回调机制),而非阻塞更侧重于线程的状态(是否被挂起)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敖云岚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值