?? sendcard.java
字號(hào):
//【例9.10】 使用管道流實(shí)現(xiàn)發(fā)牌程序。
import java.io.*;
public class SendCard //發(fā)牌程序
{
public SendCard(int n) throws IOException //n指定多少人玩牌
{
PipedInputStream[] in = new PipedInputStream[n]; //管道輸入流對(duì)象數(shù)組
PipedOutputStream[] out = new PipedOutputStream[n]; //管道輸出流對(duì)象數(shù)組
for(int i=0;i<in.length;i++)
{
in[i] = new PipedInputStream(); //創(chuàng)建一個(gè)管道輸入流對(duì)象
out[i] = new PipedOutputStream(in[i]); //創(chuàng)建一個(gè)管道輸出流對(duì)象并建立連接
}
new Sender(out, 12).start(); //啟動(dòng)一個(gè)發(fā)送線(xiàn)程
for(int i=0;i<in.length;i++) //啟動(dòng)多個(gè)接收線(xiàn)程
new Receiver(in[i]).start();
}
public SendCard() throws IOException
{
this(4); //默認(rèn)是4個(gè)人玩牌
}
public static void main (String args[]) throws IOException
{
new SendCard(); //4個(gè)人玩牌
}
}
class Sender extends Thread //發(fā)送線(xiàn)程
{
private PipedOutputStream[] out;
private int max;
public Sender(PipedOutputStream[] out,int max)
{
this.out= out;
this.max= max; //最大牌數(shù)
}
public Sender(PipedOutputStream[] out)
{
this(out,52);
}
public void run() //線(xiàn)程體
{
System.out.print("Sender: ");
int k=1;
try
{
while (k<=this.max)
{
for(int i=0; k<=this.max && i<out.length; i++)
{
this.out[i].write(k);
System.out.print(k+" ");
k++;
}
}
for(int i=0;i<out.length;i++)
this.out[i].close(); //關(guān)閉管道輸出流
System.out.println();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
class Receiver extends Thread //接收線(xiàn)程
{
private PipedInputStream in;
public Receiver(PipedInputStream in)
{
this.in = in;
}
public void run()
{
System.out.print("Receiver: "+this.getName()+" ");
try
{
int i=-1;
do //輸入流未結(jié)束時(shí)
{
i = this.in.read();
if (i!=-1)
System.out.print(i+" ");
}while (i!=-1);
System.out.println();
this.in.close(); //關(guān)閉管道輸入流
}
catch(IOException e)
{
System.out.println(e);
}
}
}
/*
程序運(yùn)行結(jié)果如下:
Sender: 1 2 3 4 5 6 7 8 9 10 11 12
Receiver: Thread-1 1 5 9
Receiver: Thread-2 2 6 10
Receiver: Thread-3 3 7 11
Receiver: Thread-4 4 8 12
new SendCard(3); //3個(gè)人玩牌
Sender: 1 2 3 4 5 6 7 8 9 10 11 12
Receiver: Thread-1 1 4 7 10
Receiver: Thread-2 2 5 8 11
Receiver: Thread-3 3 6 9 12
*/
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -