Mutex Locks in Java
In the field of computer science, mutual exclusion or mutex is known as the property of concurrency control. Every computer uses a minimum sequence of program instructions called a thread. At a time, the computer works on one thread. For better understanding, let us delve into more aspects.
Threads and multithreading
The CPU works on threads for multitasking. Each process is constantly shifting from one thread to another at a very fast speed. For example, when we watch a video, the audio of the video is on a different thread and the picture is on another thread. This constant switching between the two is very fast and it is called multithreading.
Threads in Java
Creating threads in Java is done by extending classes and implementing interfaces. Multithreading is a Java feature that allows two or more parts of a program to be executed simultaneously to maximize CPU efficiency. A thread is a component of such a program. Hence, a thread is a lightweight process within a process.
Mutex
In a multithreaded program, two or more threads may need to access shared resources at the same time, resulting in unexpected behavior. Data structures, input-output devices, files, and network connections are all examples of shared resources.
It is called a race condition. The critical section of a program is the portion of the program that accesses shared resources. Therefore, we must synchronize access to the critical section to avoid race conditions.
The most basic kind of synchronizer is the mutual exclusion (or mutex), which ensures that only one thread can run a basic area of a computer program at a time. It semaphore
is implemented by a class called .
A thread acquires the mutex, then accesses the critical section and finally releases the mutex to access the critical section. Meanwhile, all other threads are blocked until the mutex is released. A thread can enter the critical section as soon as it exits the critical section.
For a mutex, there are two methods for locking and unlocking. They are called acquire()
and respectively release()
. Now let's look at the following example.
import java.util.LinkedList; // linked list import
import java.util.concurrent.Semaphore; // semaphore import
public class Mutex {
static LinkedList<String> WorkingQueue = new LinkedList<String>();
// track the record of works
static Semaphore mutex1 = new Semaphore(0); // creating a Semaphore To ImplementLogic
static Semaphore mutex = new Semaphore(1); // Creating A Mutex
}
In the above example, we created two Mutex objects named mutex
and mutex1
. We will use mutex1
to control the switching between the two threads. The reason for creating a linked list is to keep track of the threads. Now, let's add two threads to the above code. The names of the two threads are Producer
and Consumer
.
import java.util.LinkedList; // linked list import
import java.util.concurrent.Semaphore; // semaphore import
public class Mutex {
static LinkedList<String> WorkingQueue = new LinkedList<String>();
// track the record of works
static Semaphore mutex1 = new Semaphore(0); // creating a Semaphore To ImplementLogic
static Semaphore mutex = new Semaphore(1); // Creating A Mutex
static class Producer extends Thread {
public void run() { // default run method of thread
int counter = 1;
try {
while (true) {
String threadName = Thread.currentThread().getName()
+ counter++; // counter is added to have the thread number being used
mutex.acquire(); // Acquiring Lock before Producing so the consumer cannot consume.
WorkingQueue.add(threadName);
System.out.println("Producer is prdoucing producing: " + threadName);
mutex.release(); // releasing After Production ;
mutex1.release(); // relesing lock for consumer...so consumer can consume after production
Thread.sleep(2000); // just to Reduce the Execution Speed
}
} catch (Exception e) { /*nothing */
}
}
}
static class Consumer extends Thread {
String consumerName;
public Consumer(String name) {
this.consumerName = name;
}
public void run() {
try {
while (true) {
mutex1.acquire(); /// Again Acquiring So no production while consuming
mutex.acquire(); // Acquring Other consumers lock one consume at one time
String result = "";
for (String value : WorkingQueue) {
result = value + ",";
}
System.out.println(consumerName + " consumes value: " + result
+ "Total Size working Queue Size " + WorkingQueue.size() + "\n");
mutex.release(); // releasing lock for other consumers.
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
Producer producer = new Producer();
producer.start();
Consumer c1 = new Consumer("Bill Gates");
Consumer c2 = new Consumer("Jeff Bezoz");
Consumer c3 = new Consumer("Mark Zukerberg");
c1.start();
c2.start();
c3.start();
}
}
}
explain
The code above is also self-explanatory, but this explanation will clear up the confusion.
Producer
Threads
When you run the above program, it will create a producer
thread. In that thread, there is a while
loop which will run infinitely. The string threadName
is only used to show the thread execution. The object mutex
will acquire the lock for the consumer thread to work properly. (The main purpose of Mutex, to gain concurrency control).
After that, producer
the thread starts running. Then we have to release this thread to produce. In producer
the thread, we will release mutex1
, the object that handles the switching between consumer
and . After the release, the consumer will start consuming, in other words, the thread will work.producer
消费者
Consumer
Threads
As soon as we enter consumer
the thread, we immediately acquire mutex1
to stop production during consumption. As you can see, we create three consumers under the names C1
, , C2
and C3
. To allow one consumer to run at a time, we also acquire a mutex lock.
After that, C1
will become a function, while C2
and C3
will be recycled. Once completed, mutex
will be released again, allowing other consumers to function.
This is how mutex locks work in Java. After running the above program, it will constantly display 生产者
the number of threads currently using it, along with the name of the thread using it 消费者
.
As the program runs, the size will continue to increase.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to compare characters for equality in Java
Publish Date:2025/04/14 Views:128 Category:Java
-
This tutorial shows you how to check if two characters are equal in Java. In Java, we can use the equals( == ) operator or the Character compare() equals() method of the Character class to compare two characters. If you are working with pri
Compile multiple Java files with a single command in Java
Publish Date:2025/04/14 Views:192 Category:Java
-
This tutorial explains how to compile multiple java files using a single command in Java. Compilation is a term used to refer to the process of converting java source code into bytecode using JDK. To execute any Java file, we need to follow
Arrow operator in Java ->
Publish Date:2025/04/14 Views:113 Category:Java
-
This tutorial explains - the role of the arrow operator ( ) in Java and lists some sample code to understand the topic. In Java 8, a new feature lambda expression was added, and the arrow operator appeared in Java to form lambda expressions
>> operator in Java
Publish Date:2025/04/14 Views:66 Category:Java
-
This guide will introduce you to the operator in Java . To understand this concept, you need to be familiar with some lower-level computing concepts. For example, bits, bytes, etc. Let's take a deeper look. Operators in Java In Java, the op
如何在 Java 中延迟几秒钟的时间
Publish Date:2023/12/17 Views:223 Category:Java
-
本篇文章主要介绍如何在 Java 中制造程序延迟。本教程介绍了如何在 Java 中制造程序延时,并列举了一些示例代码来了解它。
如何在 Java 中把 Hashmap 转换为 JSON 对象
Publish Date:2023/12/17 Views:190 Category:Java
-
它描述了允许我们将哈希图转换为简单的 JSON 对象的方法。本文介绍了在 Java 中把 Hashmap 转换为 JSON 对象的方法。我们将看到关于创建一个 hashmap,然后将其转换为 JSON 对象的详细例子。
如何在 Java 中按值排序 Map
Publish Date:2023/12/17 Views:172 Category:Java
-
本文介绍了如何在 Java 中按值对 Map 进行排序。本教程介绍了如何在 Java 中按值对 Map
进行排序,并列出了一些示例代码来理解它。
如何在 Java 中打印 HashMap
Publish Date:2023/12/17 Views:198 Category:Java
-
本帖介绍了如何在 Java 中打印 HashMap。本教程介绍了如何在 Java 中打印 HashMap 元素,还列举了一些示例代码来理解这个主题。
在 Java 中更新 Hashmap 的值
Publish Date:2023/12/17 Views:152 Category:Java
-
本文介绍了如何在 Java 中更新 HashMap 中的一个值。本文介绍了如何在 Java 中使用 HashMap 类中包含的两个方法-put() 和 replace() 更新 HashMap 中的值。