1.Reader
1.1 继承关系
public abstract class Reader implements Readable, Closeable{}
//下面是两个接口所需要实现的类
public interface Readable {
public int read(java.nio.CharBuffer cb) throws IOException;
}
public interface Closeable {
public void close() throws IOException;
}
1.2 部分方法
//两个未实现的方法
abstract public void close() throws IOException;
abstract public int read(char cbuf[], int off, int len) throws IOException;
//一个对象锁,这个会在构造方法中进行赋值。
protected Object lock;
protected Reader() {
this.lock = this;
}
//这个锁会在skip方法中出现
synchronized (lock) {
//这里是读操作,读多少个字符。还有判断可能文件尾
}
1.3 锁的基本介绍
上面方法中用到的锁在使用时,使用不带锁的方法是不受影响的,只有两个方法同时带锁才会受影响.
下面是写的一个例子,了解锁起到的作用。
public static void main(String args[]) throws Exception {
final Object w = new Object();
Thread t = new Thread() {
public void run() {
try {
System.out.println("线程开始,先休息0.01s,这样可以保证主线程的锁先启动");
Thread.sleep(10);
System.out.println(w+"这里可以表明使用w对象的方法的");
System.out.println("等待主线程的同步块完成");
synchronized (w) {
System.out.println("进入线程同步块");
Thread.sleep(1000);
System.out.println("线程同步结束");
}
System.out.println("线程结束");
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
synchronized (w) {
System.out.println("主线程的同步开始");
Thread.sleep(1000);
System.out.println("主线程的同步结束");
}
}
//输出结果:
主线程的同步开始
线程开始,先休息0.01s,这样可以保证主线程的锁先启动
java.lang.Object@1fb8ee3这里可以表明使用w对象的方法的
等待主线程的同步块完成
主线程的同步结束
进入线程同步块
线程同步结束
线程结束
2.Writer
2.1 继承关系
public abstract class Writer implements Appendable, Closeable, Flushable {}
public interface Appendable {
Appendable append(CharSequence csq) throws IOException;
Appendable append(CharSequence csq, int start, int end) throws IOException;
Appendable append(char c) throws IOException;
}
//其他两个接口就不需要看了。
2.2 部分方法
首先是看一看append方法
//很明显是直接写入了。
public Writer append(CharSequence csq) throws IOException {
if (csq == null)
write("null");
else
write(csq.toString());
return this;
}
再看看几个抽象方法
abstract public void write(char cbuf[], int off, int len) throws IOException;
abstract public void flush() throws IOException;
abstract public void close() throws IOException;
2.3 与锁有关的
关于写操作的内容都会加锁。
3.结束
希望继续关注字符流的其他类