- 基于字节操作的I/O接口: InputStream 和 OutputStream
- 基于字符操作的I/O接口: Writer 和 Reader
- 基于磁盘操作的I/O接口: File
- 基于网络操作的I/O接口: Socket
2, 影响网络传输的因素
- 网络带宽: 带宽指一条物理链路在1s 内能够传输的最大比特数,b/s, 平均网络带宽只有 1.7Mb/s。
- 传输距离
- TCP拥塞控制:设定一个拥塞窗口大小= 带宽* RTT(来回时间)
3,NIO
- 非阻塞
- 面向缓冲区Buffer
- 选择器Selector:Selector可以轮询每个Channel状态,只有Channel通道中的数据准备好了,才会被Selector选择。
public class AsyncResult {
private byte[] result;
private AtomicBoolean done = new AtomicBoolean(false);
private Lock lock = new ReentrantLock();
private Condition condition;
private long startTime;
public AsyncResult(){
condition = lock.newCondition();//创建一个锁
startTime = System.currentTimeMillis();
}
//检查需要的数据是否已经返回,如果没有返回,阻塞
public byte[] get(){
lock.lock();
try{
if(!done.get()){
condition.await();
}
}catch(InterruptedException e){
throw new AssertionError(e);
}finally{
lock.unlock();
}
return result;
}
//检查数据是否已经返回
public boolean isDone(){
return done.get();
}
//检查在指定的时间内需要的数据是否已经返回,如果没有返回,抛出超时异常
public byte[] get(long timeout, TimeUnit tu)throws TimeoutException{
lock.lock();
try{
boolean bval = true;
try{
if(!done.get()){
long overtime = timeout - (System.currentTimeMillis() - startTime);
if(overtime>0){
bval = condition.await(timeout, TimeUnit.MILLISECONDS);
}else
bval = false;
}
}catch(InterruptedException e){
throw new AssertionError(e);
}
if(!bval && !done.get()){
throw new TimeoutException("Operation time out!");
}
}finally{
lock.unlock();
}
return result;
}
//该函数供另一个线程设置要返回的数据,并唤醒在阻塞的线程
}
3,设计模式-适配器模式
- 适配器模式: 把一个类的接口变换成客户端所能接受的另一种接口,从而使两个接口不匹配而无法在一起工作两个类能够在一起工作。
- 通常被用在一个项目需要引用一些开源框架来一起工作的情况下, 这些框架的内容都有一些环境信息的接口,需要从外部传入,但外部的接口不一定能匹配,就需要适配器模式来转换接口。
例如: InputStreamReader 和 OutputStreamWriter 的作用也就是将 InputStream 和OutputStream 适配到Reader 和 Writer。
4,设计模式之 装饰器模式 decorate
- Component:
- ConcreteComponent
- Decorate
- ConcreteDecorate
总结:
- ConcreteDecorate
- 适配器模式: 将一个接口转换成另一个接口,通过改变接口来达到重复使用的目的。
- 装饰器模式:不是要改变被装饰的接口,而是要保持原有的接口,但增强原有对象的功能。