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 (), which can be used to designSemaphoresClass: mysemaphore, which is counted according to Dijkstra.Semaphores.
Mysemaphore has two most important member Methods: P () and V (). The two methods are actually implemented.SemaphoresP and V Operations. 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 recordsSemaphoresThe 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
ConcurrencyProgramPipeline is usually used for communication between multiple threads. 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, we found thatSource codeThere is a defect in releasing resources when processing and disabling, 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;
}