目录
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();
}
异步和非阻塞的区别:异步更侧重于任务的处理方式(回调机制),而非阻塞更侧重于线程的状态(是否被挂起)