鉴于上次惨痛的教训,我决定重新认识下java。昨天没事儿的时候把《疯狂java讲义》(李刚著)中关于线程通信的部分例子敲了一遍。coding~
代码:
PipedWriter、PipedReader做connect链接完成线程之间通信。
代码:
package thread.pipe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PipedReader;
public class ReaderThread extends Thread {
private PipedReader pr;
private BufferedReader br;
public ReaderThread() {
}
public ReaderThread(PipedReader pr) {
this.pr = pr;
this.br = new BufferedReader(pr);
}
public void run() {
String buf = null;
try {
while ((buf = br.readLine()) != null) {
System.out.println(buf);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package thread.pipe;
import java.io.IOException;
import java.io.PipedWriter;
public class WriterThread extends Thread {
String[] books = new String[] { "php", "java", "C++", "ajax" };
private PipedWriter pw;
public WriterThread() {
}
public WriterThread(PipedWriter pw) {
this.pw = pw;
}
public void run() {
try {
for (int i = 0; i < 100; i++) {
pw.write(books[i % 4]+":"+i+ "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pw != null)
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package thread.pipe;
import java.io.PipedReader;
import java.io.PipedWriter;
public class Test {
public static void main(String[] args) {
PipedWriter pw = null;
PipedReader pr = null;
try {
pw=new PipedWriter();
pr=new PipedReader();
pr.connect(pw);
new WriterThread(pw).start();
new ReaderThread(pr).start();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
PipedWriter、PipedReader做connect链接完成线程之间通信。