java线程同步之管道通信
程序员文章站
2024-02-02 08:31:28
...
之前看书的时候就看过,线程之间通信的两种方式,共享变量和管道通信,一直不知道管道通信是什么,今天终于看到了,话不多数,直接show the code
注意一点就是
这一句,其实很好理解,两个管道要连通才可以生效,不然就会出问题
public class Pipe { public static void main(String[] args) throws IOException, InterruptedException { PipedWriter out = new PipedWriter(); PipedReader in = new PipedReader(); int recive = 0; out.connect(in); Thread printThread = new Thread(new PrintThread(in),"printThread"); TimeUnit.SECONDS.sleep(5); printThread.start(); while ((recive = System.in.read()) != -1){ out.write(recive); } } static class PrintThread implements Runnable{ private PipedReader in; public PrintThread(PipedReader in) { this.in = in; } public void run() { try { int recive = 0; while ( (recive = in.read()) != -1){ System.out.print( (char) recive); } } catch (IOException e) { e.printStackTrace(); } } } } //控制台输出: 123 printThread 1 printThread 2 printThread 3
注意一点就是
out.connect(in);
这一句,其实很好理解,两个管道要连通才可以生效,不然就会出问题