Java programming skills (semaphore, pipeline)

zhaozj2021-02-16  63

Java programming skills (semaphore, pipeline) This article comes from: http://noc.cstnet.net.cn/ 宏阳 (2001-06-08 15:00:00)

First, the amount of semaphoids are often used when performing multi-thread programming, but Java itself does not provide synchronous muteting institutions, only two methods related to synchronous mutual exclusion: Wait () and notify () It can be used to design a quantity class: MySemaphore, which is designed according to Dijkstra. MySemaphore has two most important members: P () and v (). These two methods actually realize the P operation and V operation of the semaphore. Described as follows: public synchronized void P () {semaphore--; if (semaphore <0) {try {wait ();} catch (InterruptedException ie) {}}} public synchronized void V () {semaphore ; if (semaphore <= 0) NOTIFY ();} where the Semaphore variable records the state of the semaphore, the wait () method is equivalent to the block primitive, used to block the execution of the thread, the notify () method is equivalent to Wakeup primitives for waking up Thread recovery run. Since these two methods are defined as synchronized, the Java virtual machine ensures that the atoms of the two methods are implemented, thereby implementing P, V operation. Second, the communication between multiple threads of the pipeline concurrent program is usually made using the pipeline, and the JDK provides two pipe classes: PipedInpustream and PipedputStream, for input, the latter used to output. These two pipes should be able to connect and closing multiple times. During implementation, they find that they cannot be re-established after shutting down. After careful debugging, it is found that the source code of JDK releases the resource when processing the shutdown, so you need to write your own pipeline class: MypipedinputStream and MyPipedOutputStream. These two classes are inherited directly from InputStream and OutputStream, and their membership methods are all consistent with PiPedInputStream and PiPedoutputStream, just when processing shutdown, restore the value of member variables in the category to the initial value when unconnected. In addition, the original pipeline provides only 1024 bytes, and the output can be overflow when the amount of data is transmitted, and the pipe capacity can be arbitrarily set in its own pipe class, for example, the pipe capacity can be used as needed. Set to 64KB. Only the corresponding shutdown routines are given below: 1. MypipedinputStream Public Void Close () throws ioException {IN = -1; OUT = 0; ClosedByReader = true; connection = false; closed = true; buffer = new byte [PIPE_SIZE];} 2. MypipedOxce () THROWS IOException {if (sink! = Null) {sink.receivedlast (); sink.closed = true;} SINK = null; connection = false;

转载请注明原文地址:https://www.9cbs.com/read-18787.html

New Post(0)