1. Semaphore
Let’s talk about Semaphore first. Semaphore can control the number of resources that can be accessed simultaneously, obtain a license through acquire(), wait if there is no, and release() releases a license. It is generally used to control the number of concurrent threads and mutual exclusion between threads. In addition, the reentrantLock can also implement this function, but the implementation is more complicated.
The function is similar to all 5 pits in the toilet. If 10 people have to go to the toilet, then how many people can only go to the toilet at the same time? At the same time, only 5 people can occupy it. When any of the five people moves aside, one of the other 5 people waiting can occupy it. In addition, among the 5 people waiting, they can get priority opportunities at random, or they can get opportunities in order of first come and then arrive.
A single semaphore object can implement the function of a mutex, and it can be obtained by one thread and released by another thread. This can be applied in some cases of deadlock recovery.
example:
/** * @Description: * @param @param args * @return void Return type*/public static void main(String[] args) { // thread pool ExecutorService exec = Executors.newCachedThreadPool(); // Only 5 threads can access final Semaphore semp = new Semaphore(5); // Simulate 20 client access for (int index = 0; index < 20; index++) { final int NO = index; Runnable run = new Runnable() { public void run() { try { // Get permission semp.acquire(); System.out.println("Get Accessing: " + NO); Thread.sleep((long) (Math.random() * 10000)); // After accessing, release semp.release(); System.out.println("Remainableavailable signals----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Output result (think why it outputs like this):
Obtain Accessing: 1 Obtain Accessing: 5 Obtain Accessing: 2 Obtain Accessing: 3 Obtain Accessing: 0 Remaining Available Signal---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 13 Remainable signals ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2. Use PIPE as a bridge between threads
Pipe has a source channel and a sink channel. The data will be written to the sink channel and read from the source channel. One in and one out. Let’s first learn how to use it.
It is worth noting that under java.nio.channels, this class indicates that the data communication method of the nio method is used, so use a Buffer to buffer data.
Illustration of Pipe principle:
Pipe is an empty pipe. One end of this empty pipe can be read from the inside of the pipe and the other end can be written into the pipe.
Operation process:
1. First, there must be an object to write it into this empty tube. Where to write? This empty pipe has a little space, right in this pipe.
When writing, it is written into the space contained in the pipe itself. This space size is 1024 bytes.
2. Then another object can read out the contents of this filled tube.
On the code
package com.jx.test;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Pipe;public class testPipe {/** * @Description: * @param @param args * @return void Return type* @throws IOException */public static void main(String[] args) throws IOException {// Create a pipeline Pipe pipe = Pipe.open();final Pipe.SinkChannel psic = pipe.sink();// To write data to the pipeline, you need to access the sink channel final Pipe.SourceChannel psoc = pipe.source();// From reading the data of the pipeline, you need to access the source channel Thread tPwriter = new Thread() {public void run() {try {System.out.println("send......");// Create a thread and use the pipe's write port Pipe.SinkChannel type psic to write the content of the specified ByteBuffer into the pipeline int res = psic.write(ByteBuffer .wrap("Hello,Pipe! Test communication......".getBytes("utf-16BE")));System.out.println("send size:" + res);}catch (Exception e) {e.printStackTrace();}}};Thread tPreader = new Thread() {public void run() {int bbufferSize = 1024 * 2;ByteBuffer bbuffer = ByteBuffer.allocate(bbufferSize);try {System.out.println("recive......");// Create a thread and use the read entry of the pipeline Pipe.SourceChannel type psoc to read the contents in the pipeline into the specified ByteBuffer int res = psoc.read(bbuffer);//The data is not System.out.println("recive size:"+res+" Content:" + ByteBufferToString(bbuffer));}catch (Exception e) {e.printStackTrace();}}};tPwriter.start();tPreader.start();}/** *ByteBuffer--> String's conversion function*/public static String ByteBufferToString(ByteBuffer content) {if (content == null || content.limit() <= 0 || (content.limit() == content.remaining())) {System.out.println("Not exists or the content is empty!");return null;}int contentSize = content.limit() - content.remaining();StringBuffer resultStr = new StringBuffer();for (int i = 0; i < contentSize; i += 2) {resultStr.append(content.getchar(i));}return resultStr.toString();}}Summarize
The above is all about the examples of Java programming inter-thread communication and semaphore code in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!