阻塞与同步的区别:
阻塞影响代码继续向后执行;
同步可以不阻塞从任务理解A的完成依赖B的完成,A可以继续做其它的事情(银行办业务,在抽取号之后就可以做其它的事情不用一直站着排队)
阻塞的本质
服务端
package com.zyl.netio.blocking;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws Exception {
Server server = new Server(9090);
server.start();
}
static class Server {
private ServerSocket serverSocket;
private ThreadPoolExecutor executor;
public Server(int port) {
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(port));
executor = new ThreadPoolExecutor(10, 30, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(30));
System.out.println("服务已经启动...");
} catch (Exception exp) {
exp.printStackTrace();
}
}
public void start() {
while (true) {
try {
Socket accept = serverSocket.accept();
System.out.println(accept.getInetAddress().getHostAddress() + " 已经连接");
executor.execute(new Handle(accept));
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
}
static class Handle implements Runnable {
private Socket socketChannel;
public Handle(Socket socketChannel) {
this.socketChannel = socketChannel;
}
@Override
public void run() {
try {
BufferedReader bufInstream = new BufferedReader(new InputStreamReader(socketChannel.getInputStream()));
while (true) {
String line = null;
while (null != (line = bufInstream.readLine())) {
System.out.println(line);
socketChannel.getOutputStream().write("Hello Client\r\n".getBytes(StandardCharsets.UTF_8));
socketChannel.getOutputStream().flush();
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
}
客户端
package com.zyl.netio.blocking;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Client {
public static void main(String[] args) {
try {
Socket socketChannel = new Socket();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 9090));
new Thread(() -> {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socketChannel.getInputStream()));
while (true) {
String line = null;
while (null != (line = bufferedReader.readLine())) {
System.out.println(line);
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}).start();
while (true) {
socketChannel.getOutputStream().write("Hello Server\r\n".getBytes(StandardCharsets.UTF_8));
Thread.sleep(1000);
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}