栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-14

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-14

多线程(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 {
        
        for (int i = 0; i < 100; i++) {
            String data = "-" + i;
            out.write(data.getBytes()); //把字节数组写入到输出管道流中
        }
        out.close();
    }

    
    public static void readData(PipedInputStream input) throws IOException {
        
        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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325364.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号