Java pipe streams: Another option for Android inter-thread communication

Not for anything else, just for the interviewer to check...

PipedInputstream and PipedOutputStream are inter-thread communication APIs in the Java1.1 era, but they seem to be rarely mentioned, perhaps because they are used in fewer scenarios, and there are simply too many inter-thread communication solutions...

This API is reserved in the Android field, and you can also use it to do Handler things. The general steps to use are as follows

  1. Initialize pipeline
  2. connecting pipes
  3. Open communication in their own thread

advantage:

1. The streamlined process can easily find both ends of the data, and the Handler can send everywhere

2. It seems that any data can be transmitted, including large chunks of streaming data, binary data, etc.

shortcoming:

It is troublesome to use, and there are two more threads inside PipedOutputStream, one for reading and one for writing, and more threads are opened at the application level. A read and write function may require at least three threads, which is relatively expensive...

Summary :

Not very useful, just another way of writing "fennel"...

demo

The following demonstrates how to accept the data sent by the child thread and then update it to the main thread


public class Demo2MainActivity extends AppCompatActivity {
    
    
    private TextView textViewLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo2_main);
        textViewLabel = findViewById(R.id.textViewLabel2);
        setTitle("Java管道流用户Android线程间通信");

        //1.初始化管道
        PipedInputStream pins = new PipedInputStream();
        PipedOutputStream pouts = new PipedOutputStream();

        try {
    
    
            pins.connect(pouts);//2.连接管道
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

        //====================各自线程种执行数据收发============
        //3.开启子线程,子线程发法消息到主线程
        new SubThread(pouts, new WeakReference<>(this)).start();

        //4.接收到子线程发出来的数据,更新到主线程UI
        new Thread(() -> {
    
    
            byte[] buf = new byte[512];
            while (true) {
    
    
                int ret = 0;
                try {
    
    
                    ret = pins.read(buf);
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
                String received = new String(buf, 0, ret);
                textViewLabel.post(() -> textViewLabel.setText("主线程接到的子线程数据:\n" + received));
            }
        }).start();

    }

    /**
     * 在子线程中不断向主线程发消息
     */
    public static class SubThread extends Thread {
    
    
        public SubThread(PipedOutputStream pipedOutputStream, WeakReference<Activity> activityWeakReference) {
    
    
            super(() -> {
    
    
                while (true) {
    
    
                    if (null == activityWeakReference.get() || activityWeakReference.get().isFinishing()) {
    
    
                        break;
                    }
                    try {
    
    
                        if (null != pipedOutputStream) {
    
    
                            pipedOutputStream.write(("子线程名:" + Thread.currentThread().getName() + "  数据:" + System.currentTimeMillis() + "\n").getBytes(StandardCharsets.UTF_8));
                        }
                        Thread.sleep(1000);
                    } catch (Exception e) {
    
    
                        e.printStackTrace();
                    }
                }
            });
        }
    }

}

renderings

demo.gif

Guess you like

Origin blog.csdn.net/wang382758656/article/details/124321360