找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 查看内容

java管道流写入报错

作者:模板之家 2021-1-10 14:37 89人关注

java管道流写入报错:1.创建和连接管道两端的两种方法;2.写入报错分析,在线程Sender中向管道流中写入一个字符串,写入后关闭该管道流,会抛出“Write end dead”异常。

在使用管道流时,如果写入后对该通道进行关闭,就会出现报错的情况。那么具体出错的原理,想必很多人不清楚,关于这点在线程的操作时有讲到,管道存在于线程中。下面我们就先来学习管道创建的方法,然后进行对线程的关闭测试,在其中找到管道流报错的原因。

1.创建和连接管道两端的两种方法

1)创建管道输入和输出流并连接它们。它使用connect方法连接两个流。

PipedInputStream pis  = new PipedInputStream(); 
PipedOutputStream pos  = new PipedOutputStream(); 
pis.connect(pos); /* Connect  the   two  ends  */

2)创建管道输入和输出流并连接它们。它通过将输入管道流传递到输出流构造器来连接两个流。

PipedInputStream pis  = new PipedInputStream(); 
PipedOutputStream pos  = new PipedOutputStream(pis);

2.写入报错分析

在线程Sender中向管道流中写入一个字符串,写入后关闭该管道流;在线程Reciever中读取该字符串。

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
public class PipedStreamExam1 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
 
        try {
            //创建管道流
            PipedOutputStream pos = new PipedOutputStream();
            PipedInputStream pis = new PipedInputStream(pos);
 
            //创建线程对象
            Sender sender = new Sender(pos);
            Reciever reciever = new Reciever(pis);
 
            //运行子线程
            executorService.execute(sender);
            executorService.execute(reciever);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //等待子线程结束
        executorService.shutdown();
        try {
            executorService.awaitTermination(1, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    static class Sender extends Thread {
        private PipedOutputStream pos;
 
        public Sender(PipedOutputStream pos) {
            super();
            this.pos = pos;
        }
 
        @Override
        public void run() {
            try {
                String s = "This is a good day. 今天是个好天气。";
                System.out.println("Sender:" + s);
                byte[] buf = s.getBytes();
                pos.write(buf, 0, buf.length);
                pos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    static class Reciever extends Thread {
        private PipedInputStream pis;
 
        public Reciever(PipedInputStream pis) {
            super();
            this.pis = pis;
        }
 
        @Override
        public void run() {
         & 

路过

雷人

握手

鲜花

鸡蛋
来自: Python学习网

全部回复(0)