多线程通信学习

鉴于上次惨痛的教训,我决定重新认识下java。昨天没事儿的时候把《疯狂java讲义》(李刚著)中关于线程通信的部分例子敲了一遍。coding~
代码:

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链接完成线程之间通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值