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

📄 sendcard1.java

📁 《Java2程序设计实用教程(第2版)》课件
💻 JAVA
字号:
//使用管道流在两个线程对象之间传数据。

import java.io.*;

public class SendCard1
{
    public SendCard1() throws IOException
    {
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        in.connect(out);
        
        new Sender(out,12).start();
        new Receiver(in).start();
    }
    
    public static void main (String args[]) throws IOException
    {
        new SendCard1();
    }
}

class Sender extends Thread                      //发送线程
{
    private PipedOutputStream out;
    private int max;
    
    public Sender(PipedOutputStream out,int max)
    {
        this.out= out;
        this.max= max;
    }
    
    public Sender(PipedOutputStream out)
    {
        this(out,10);
    }

    public void run()
    {
        System.out.print("Sender:  ");
        int i=1;
        try 
        {
            while (i<=this.max)
            {
                this.out.write(i);
                System.out.print(i+"  ");
                i++;
            }
            
            this.out.close();                         //关闭管道输出流
            System.out.println("  out closed!");
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
    }
}

class Receiver extends Thread                    //接收线程
{
    private PipedInputStream in;
    
    public Receiver(PipedInputStream in)
    {
        this.in = in;
    }
    
    public void run()
    {
        System.out.print("Receiver: "+this.getName()+"  ");
        try
        {
            int i=-1;
            do                                   //输入流未结束时
            {
                i = this.in.read();
                System.out.print(i+"  ");
            }while (i!=-1);
            
            this.in.close();                          //关闭管道输入流
            System.out.println("  in closed!");
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
    }
}


/*
析构方法??不自动执行
SendCard
    public void finalize()// throws IOException                     //析构方法
    {

            System.out.println("finalize");

//        try
  //      {
//        in.close();
//        out.close();
    //    }
      //  catch(IOException ioe)
        //{  }
    }

Sender
    public void finalize()                      //析构方法??不自动执行
    {
            System.out.println("Sender finalize");
        count--;
    }


*/

⌨️ 快捷键说明

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