PipedCharacters.java
资源名称:Source.rar [点击查看]
上传用户:songled
上传日期:2022-07-14
资源大小:94k
文件大小:2k
源码类别:
进程与线程
开发平台:
Java
- import java.io.*;
- public class PipedCharacters extends Object {
- public static void writeStuff(Writer rawOut) {
- try {
- BufferedWriter out = new BufferedWriter(rawOut);
- String[][] line = {
- { "Java", "has", "nice", "features." },
- { "Pipes", "are", "interesting." },
- { "Threads", "are", "fun", "in", "Java." },
- { "Don't", "you", "think", "so?" }
- };
- for ( int i = 0; i < line.length; i++ ) {
- String[] word = line[i];
- for ( int j = 0; j < word.length; j++ ) {
- if ( j > 0 ) {
- // put a space between words
- out.write(" ");
- }
- out.write(word[j]);
- }
- // mark the end of a line
- out.newLine();
- }
- out.flush();
- out.close();
- } catch ( IOException x ) {
- x.printStackTrace();
- }
- }
- public static void readStuff(Reader rawIn) {
- try {
- BufferedReader in = new BufferedReader(rawIn);
- String line;
- while ( ( line = in.readLine() ) != null ) {
- System.out.println("read line: " + line);
- }
- System.out.println("Read all data from the pipe");
- } catch ( IOException x ) {
- x.printStackTrace();
- }
- }
- public static void main(String[] args) {
- try {
- final PipedWriter out = new PipedWriter();
- final PipedReader in = new PipedReader(out);
- Runnable runA = new Runnable() {
- public void run() {
- writeStuff(out);
- }
- };
- Thread threadA = new Thread(runA, "threadA");
- threadA.start();
- Runnable runB = new Runnable() {
- public void run() {
- readStuff(in);
- }
- };
- Thread threadB = new Thread(runB, "threadB");
- threadB.start();
- } catch ( IOException x ) {
- x.printStackTrace();
- }
- }
- }