⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pipedstream.java

📁 Java Classic Examples是我买的两本书:《JAVA经典实例》和《java入门经典源代码》里边附送光盘里带的源码
💻 JAVA
字号:
import java.io.*;
public class Pipedstream
{
    public static void main (String args[])
    {
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        try
        {
             in.connect(out);
        }
        catch(IOException ioe)   {  }
        Send s1 = new Send(out,1);
        Send s2 = new Send(out,2);
        Receive r1 = new Receive(in);
        Receive r2 = new Receive(in);
        s1.start();
        s2.start();
        r1.start();
        r2.start();
    }
}
class Send extends Thread                //发送线程
{
    PipedOutputStream out;
    static int count=0;                  //记录线程个数
    int k=0;
    public Send(PipedOutputStream out,int k)
    {
        this.out= out;
        this.k= k;
        this.count++;                    //线程个数加1
    }
    public void run( )
    {
        System.out.print("\r\nSend"+this.k+":   "+this.getName()+"  ");
        int i=k;
        try 
        {
            while (i<10)
            {
                out.write(i);
                i+=2;
                sleep(1);
            }
            if (Send.count==1)           //只剩一个线程时
            {
                out.close();             //关闭输入管道流
                System.out.println("  out closed!");
            }    
            else
                this.count--;            //线程个数减1 
        }
        catch(InterruptedException e)   {  }
        catch(IOException e)   { }
    }
}
class Receive extends Thread             //接收线程
{
    PipedInputStream in;
    public Receive(PipedInputStream in)
    {
        this.in = in;
    }
    public void run( )
    {
        System.out.print("\r\nReceive: "+this.getName()+"  ");
        try
        {
            int i = in.read();
            while (i!=-1)                //输入流未结束时
            {
                System.out.print(i+"  ");
                i = in.read();
                sleep(1);
            }
            in.close();                  //关闭输入管道流
        }
        catch(InterruptedException e)  { }
        catch(IOException e)
        {
            System.out.println(e);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -