Java Multithreading
Java Multithreading
chapter 26
Multithreading
• Multithreading in Java is a way to run multiple parts of a program at
the same time. Think of it like having multiple people working on
different parts of a project at the same time. Each person can work
independently, but they all contribute to the same goal.
The -> syntax is used to separate the lambda's parameters from its body. In the given code, the lambda
expression takes no parameters (since Runnable has no parameters) and its body is the block of code
inside the curly braces {}.
So, the lambda expression () -> { ... } is equivalent to an anonymous implementation of the Runnable
interface, like this: new Runnable() { @Override public void run() { ...} }
get name of thread
Thread.currentThread().getName());
Race condition
• A race condition in Java threading occurs when two or more threads
access shared data or resources concurrently without proper
synchronization. When a race condition occurs, the outcome of the
program depends on the order in which the threads execute, which is
unpredictable and can lead to unexpected results.
Race
• Here the output can be anything due to race condition.
Thread-0 Thread-2 Thread-2 Thread-2 Thread-2 Thread-2 Thread-1
Thread-1 Thread-1 Thread-1 Thread-1 Thread-0 Thread-0 Thread-0
Thread-0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
locking a thread
• In Java, a thread lock is a mechanism used to ensure that only one thread
can access a shared resource at a time. The purpose of a lock is to prevent
multiple threads from executing the same block of code or accessing the
same object concurrently, which could result in race conditions, data
corruption, or other issues.
• When a thread acquires a lock on an object, it gains exclusive access to
that object and can perform any operation on it. Other threads that try to
access the same object will be blocked .
• In Java, locks are implemented using the synchronized keyword or by
using explicit lock objects provided by the java.util.concurrent.locks
package.
lock() method
• We define two threads, t1 and t2, which both increment the counter
variable one million times. To ensure that access to the counter
variable is synchronized, we surround each increment operation with
calls to lock() and unlock() methods of the lock object.
• The lock() method blocks the current thread until it acquires the lock.
If the lock is already held by another thread, the current thread waits
until the lock is released. The unlock() method releases the lock,
allowing another thread to acquire it.
• In Java, try...finally blocks are commonly used for resource cleanup. In
the context of threads, try...finally blocks are often used to ensure
that locks are released in case an exception occurs while a thread
holds the lock.