1.同步和异步一般指的是io操作。阻塞和非阻塞是指线程。
同步是用户进程在触发io操作并等待,轮询的去查看io操作是否就绪。异步是触发io操作之后还能进行其他操作,当io操作完成之后也能得到通知。
阻塞是线程在得到调用结果之前一直等待。非阻塞是线程在执行完数据之后被挂起,等待下次被唤醒。
2.bio 也叫做同步阻塞型io。
处理步骤: 客户端发送请求,接收器Acceptor每接收一个请求,就创建一个新线程,处理完成后,再通过输出流返回客户端,然后销毁线程。
缺陷:一个客户端请求,就对应一个线程,客户端请求和服务端的线程就成1:1的比例,当请求过多的时候,线程越来越多,jvm内存被大量占用,最后堆栈溢出,发生异常。
服务端代码:
/**
* @chenxiaowu
*2018年2月7日
*TODO
*/
public class TimeServer {
public static void main(String[] args) throws IOException {
int port=8080;
ServerSocket serverSocket=null;
try{
//创建服务端socket,绑定端口。处理完请求之后,再进入等待状态。
serverSocket=new ServerSocket(port);
System.out.println("The timeserver is start in port:"+port);
Socket socket=null;
//循环,等待客户端的请求接入,才会继续执行。
while(true)
{
//接收服务端的请求
socket=serverSocket.accept();
//启动线程
new Thread(new TimeServerHandler(socket)).start();;
}
}finally{
if(serverSocket!=null)
{
System.out.println("The timeserver is over");
serverSocket.close();
serverSocket=null;
}
}
}
}
线程启动类(返回时间):
/**
* @chenxiaowu
*2018年2月7日
*TODO
*/
public class TimeServerHandler implements Runnable{
private Socket socket;
public TimeServerHandler(Socket socket)
{
this.socket=socket;
}
public void run() {
// TODO Auto-generated method stub
BufferedReader in =null;
PrintWriter pr=null;
try{
in=new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
pr=new PrintWriter(this.socket.getOutputStream(),true);
String currentTime=null;
String body=null;
while(true)
{
body=in.readLine();
if(body==null)
{
break;
}
System.out.println("The time server accept message:"+body);
currentTime="QUERY TIME".equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString():"BAD ORDER";
pr.println(currentTime);
}
}catch(Exception e)
{
if(in !=null)
{
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(pr !=null)
{
pr.close();
}
if(socket!=null)
{
try {
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
客户端:
/**
* @chenxiaowu
*2018年2月7日
*TODO
*/
public class TimeClient {
public static void main(String[] args) {
try {
Socket socket=new Socket("127.0.0.1", 8080);
BufferedReader in= null;
PrintWriter out=null;
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new PrintWriter(socket.getOutputStream(),true);
out.println("QUERY ");
String resp=in.readLine();
System.out.print("CLIENT now:"+resp);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这段时间会持续学习 bio-nio-netty。共勉。