I. semaphores
Synchronization mutex mechanism is often used for multi-threaded programming, but java itself does not provide synchronization mutex mechanism. Only two methods related to synchronization mutex are provided: wait () and notify () can be used to design the semaphore class: mySemaphore, which is designed according to the idea of counting semaphores proposed by Dijkstra.
MySemaphore has two most important member Methods: P () and V (). The two methods actually implement the P and V Operations of the semaphore. The detailed description is as follows:
Public synchronized void P (){
Semaphore --;
If (semaphore <0 ){
Try {
Wait ();
} Catch (InterruptedException ie ){}
}
}
Public synchronized void V (){
Semaphore ++;
If (semaphore <= 0)
Notify ();
}
The semaphore variable records the semaphore state. The wait () method is equivalent to the block primitive used to block thread execution. The notify () method is equivalent to the wakeup primitive used to wake up the thread to resume running. Because these two methods are defined as synchronized, the Java Virtual Machine can ensure the atomic execution of these two methods, thus implementing the P and V Operations.
Ii. Pipelines
The communication between multiple threads of a concurrent program is usually conducted using pipelines. jdk provides two pipeline classes: PipedInpuStream and PipedOutputStream. The former is used for input and the latter is used for output. These two pipelines can be connected and closed multiple times, but they cannot be connected again after they are closed. After careful debugging, it is found that the jdk source code is defective when processing and disabling resources, so you need to write your own pipeline classes: MyPipedInputStream and MyPipedOutputStream. These two classes are inherited directly from InputStream and OutputStream. Their Member methods and implementations are basically the same as PipedInputStream and PipedOutputStream, but when processing is disabled, restores the value of the member variable in the class to the initial value when no connection is established. In addition, the pipeline capacity provided by the original pipeline is only 1024 bytes. When the data volume is large, overflow may occur. In the pipeline class, you can set the pipeline capacity as needed, for example, you can set the pipeline capacity to 64KB as needed. The following provides only corresponding close routines:
1. MyPipedInputStream
Public void close () throws IOException {
In =-1;
Out = 0;
ClosedByReader = true;
Connected = false;
Closed = true;
Buffer = new byte [PIPE_SIZE];
}
2. MyPipedOutputStream
Public void close () throws IOException {
If (sink! = Null ){
Sink. receivedLast ();
Sink. closed = true;
}
Sink = null;
Connected = false;
}