本文发表在 rolia.net 枫下论坛import java.util.*;
import java.io.*;
public class ThreadDemo {
PipedOutputStream pos = null;
PipedInputStream pis = null;
DataInputStream dis = null;
DataOutputStream dos =null;
boolean shouldRun=true;
//use the so-called inner class mechanism
Thread t1= new Thread(){
int n=0;
public void run() {
while(shouldRun){
n++;
if(n%50 ==0) {
try{
dos.writeInt(n);
} catch(IOException e) {};
}
Thread.yield();
}
}
};
//use the so-called inner class mechanism
Thread t2= new Thread(){
public void run() {
while(shouldRun){
try{
System.out.println(dis.readInt());
} catch(IOException e) {};
Thread.yield();
}
}
};
public void stop() {
shouldRun=false;
}
public ThreadDemo() throws IOException{
//Piping IO Streams between two Threads
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
dis = new DataInputStream(pis);
dos = new DataOutputStream(pos);
t1.start();
t2.start();
}
public static void main(String[] args) throws Exception {
ThreadDemo demo = new ThreadDemo();
}
}更多精彩文章及讨论,请光临枫下论坛 rolia.net
import java.io.*;
public class ThreadDemo {
PipedOutputStream pos = null;
PipedInputStream pis = null;
DataInputStream dis = null;
DataOutputStream dos =null;
boolean shouldRun=true;
//use the so-called inner class mechanism
Thread t1= new Thread(){
int n=0;
public void run() {
while(shouldRun){
n++;
if(n%50 ==0) {
try{
dos.writeInt(n);
} catch(IOException e) {};
}
Thread.yield();
}
}
};
//use the so-called inner class mechanism
Thread t2= new Thread(){
public void run() {
while(shouldRun){
try{
System.out.println(dis.readInt());
} catch(IOException e) {};
Thread.yield();
}
}
};
public void stop() {
shouldRun=false;
}
public ThreadDemo() throws IOException{
//Piping IO Streams between two Threads
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
dis = new DataInputStream(pis);
dos = new DataOutputStream(pos);
t1.start();
t2.start();
}
public static void main(String[] args) throws Exception {
ThreadDemo demo = new ThreadDemo();
}
}更多精彩文章及讨论,请光临枫下论坛 rolia.net