JAVA设计使用管道流的发牌程序

JAVA2程序设计实用教程之Java的面向对象特征上机报告|上机实验实习报告|计算机上机实习报告|JAVA设计使用管道流的发牌程序

在例7.9中我们利用线程调度设计了一个发牌程序,请结合本例,设计使用管道流的发牌程序。

import java.awt.*;

import java.awt.event.*;

import java.io.*;

public class Card extends WindowAdapter

{

    Frame f;

    TextArea ta1,ta2,ta3,ta4;

    public void display()

    {

        f = new Frame("Send Card");

        f.setSize(400,300);

        f.setLocation(200,140);

        f.setBackground(Color.lightGray);

        f.setLayout(new GridLayout(2,2));

        f.addWindowListener(this);

        ta1 = new TextArea("",5,10,3);           //文本区没有滚动条

        ta2 = new TextArea("",5,10,3);

        ta3 = new TextArea("",5,10,3);

        ta4 = new TextArea("",5,10,3);

        Font font1 = new Font("Helvetica", Font.PLAIN, 20);

        ta1.setFont(font1);ta2.setFont(font1);

        ta3.setFont(font1);ta4.setFont(font1);

        f.add(ta1);f.add(ta2);f.add(ta4);

        f.add(ta3);f.setVisible(true);

    }

    public void windowClosing(WindowEvent e)

    {

        System.exit(0);

    }

    public static void main(String arg[])

    {

        Card p = new Card();

        p.display();

        PipedInputStream in=new PipedInputStream();

        PipedOutputStream out=new PipedOutputStream();

        try

        {

            in.connect(out);

        }

        catch(IOException ioe){ }

        Sender3 s = new Sender3(out,52);

        s.start();                               //启动发牌线程

        s.setPriority(1);                        //设置最高优先级,值为1

        Receiver3 r1=new Receiver3(in,p.ta1);    //创建四个取牌线程

        Receiver3 r2=new Receiver3(in,p.ta2);

        Receiver3 r3=new Receiver3(in,p.ta3);

        Receiver3 r4=new Receiver3(in,p.ta4);

        r1.start(); r2.start(); r3.start(); r4.start();

    }

}

class Sender3 extends Thread               //发牌线程

{

    PipedOutputStream out;

    int count;

    public Sender3(PipedOutputStream out,int c)

    {

        this.out=out;

        this.count = c;

    }

    public void run( )

    {

        try{

            for (int i=1;i<=count;i++)

                out.write(i);

        }

        catch(IOException e){}

    }

}

class Receiver3 extends Thread             //取牌线程

{

    PipedInputStream in;

    TextArea ta;

    public Receiver3(PipedInputStream in,TextArea ta)

    {

        this.in=in;

        this.ta = ta ;

    }

    synchronized public void run()

    {

        while(true)

        {

            try

            {

                int i=in.read();

                if(i!=-1)

                {  

                 ta.append(" "+i); 

 wait(1000);

                }

            }

            catch(IOException e){ }

            catch(InterruptedException e)

            {

                 System.out.println(e.getMessage());

            }

        }

    }

}

结果:若图片无法显示请联系站长QQ3249114

实验总结:

 在此次实验中,掌握了Java的面向对象特征。但在程序的细节上还存在着问题。

Copyright © 2007-2012 www.chuibin.com 六维论文网 版权所有