多线程(6)
通过管道实现线程间的通信
在java.io中的 PIpeStream管道流,用于在线程之间传送数据。
一个线程发送数据到输出管道,另一个线程从输入管道中读取数据。PipeInputStream , PipeOutStream, PipeReader , PipedWriter。
public class Test {
public static void main(String[] args) throws IOException {
/*定义管道字节流*/
PipedInputStream inputStream = new PipedInputStream();
PipedOutputStream outputStream = new PipedOutputStream();
inputStream.connect(outputStream);
/*创建两个线程向管道流中读写数据*/
new Thread(new Runnable() {
@Override
public void run() {
try {
writeData(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
readData(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 定义方法向管道流中写入数据
*/
public static void writeData(PipedOutputStream out) throws IOException {
/*把0-100 之间的数写入管道中*/
for (int i = 0; i < 100; i++) {
String data = "-" + i;
out.write(data.getBytes()); //把字节数组写入到输出管道流中
}
out.close();
}
/**
* 定义方法从管道中读取数据
*/
public static void readData(PipedInputStream input) throws IOException {
/*从管道中读取0-100*/
byte[] bytes = new byte[1024];
int len = input.read(bytes); //返回读到的字节数,如果没有读到任何数据返回-1
while(len != -1){
//把bytes数组中从0开始到len个字节转换为字符串打印出来
System.out.println(new String(bytes,0,len));
len = input.read(bytes); //继续从管道中读取数据
}
input.close();
}
}
ThreadLocal()
ThreadLocal类顾名思义可以理解为线程本地变量。也就是说如果定义了一个ThreadLocal, 每个线程往这个ThreadLocal中读写是线程隔离,互相之间不会影响的。它提供了一种将可变数据通过每个线程有自己的独立副本从而实现线程封闭的机制。
如果一百个同学抢一根笔,这个笔就是共享资源。作为王老师,一定得处理这个事不然学生容易打起来,让他们一个一个的来。 ===内部锁的原理
*如果给同学提供100支笔,能更快的完成任务。====ThreadLocal()的思路*
ThreadLocal ThreadLocal的作用主要是做数据隔离,填充的数据只属于当前线程,变量的数据对别的线程而言是相对隔离的,在多线程环境下,如何防止自己的变量被其它线程篡改。
每个Thread对象都有一个ThreadLocalMap,每个ThreadLocalMap可以存储多个ThreadLocal