Telegram Group & Telegram Channel
Вопрос на собеседовании

Что такое ReentrantLock в Java, какие преимущества он имеет перед ключевым словом synchronized, и как его правильно использовать?

Ответ ⬇️
ReentrantLock — это класс из пакета java.util.concurrent.locks, предоставляющий более гибкий механизм блокировки, чем synchronized. Он поддерживает методы для явного управления блокировками, такие как tryLock() (попытка захвата без ожидания) и lockInterruptibly() (захват с возможностью прерывания). В отличие от synchronized, он позволяет справляться с блокировками вручную и поддерживает более точное управление потоками. Однако неправильное использование может привести к deadlock.

Пример использования ⚙️
import java.util.concurrent.locks.ReentrantLock;

public class Main {
private static final ReentrantLock lock = new ReentrantLock();

public static void main(String[] args) {
Thread thread1 = new Thread(Main::criticalSection, "Thread-1");
Thread thread2 = new Thread(Main::criticalSection, "Thread-2");

thread1.start();
thread2.start();
}

private static void criticalSection() {
if (lock.tryLock()) { // Пытаемся захватить блокировку
try {
System.out.println(Thread.currentThread().getName() + " выполняет критическую секцию");
Thread.sleep(1000); // Эмуляция работы
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock(); // Обязательно освобождаем блокировку
System.out.println(Thread.currentThread().getName() + " завершил работу");
}
} else {
System.out.println(Thread.currentThread().getName() + " не смог захватить блокировку");
}
}
}


Java Learning 👩‍💻
Please open Telegram to view this post
VIEW IN TELEGRAM
👍6



tg-me.com/Java_per_month/3142
Create:
Last Update:

Вопрос на собеседовании

Что такое ReentrantLock в Java, какие преимущества он имеет перед ключевым словом synchronized, и как его правильно использовать?

Ответ ⬇️
ReentrantLock — это класс из пакета java.util.concurrent.locks, предоставляющий более гибкий механизм блокировки, чем synchronized. Он поддерживает методы для явного управления блокировками, такие как tryLock() (попытка захвата без ожидания) и lockInterruptibly() (захват с возможностью прерывания). В отличие от synchronized, он позволяет справляться с блокировками вручную и поддерживает более точное управление потоками. Однако неправильное использование может привести к deadlock.

Пример использования ⚙️

import java.util.concurrent.locks.ReentrantLock;

public class Main {
private static final ReentrantLock lock = new ReentrantLock();

public static void main(String[] args) {
Thread thread1 = new Thread(Main::criticalSection, "Thread-1");
Thread thread2 = new Thread(Main::criticalSection, "Thread-2");

thread1.start();
thread2.start();
}

private static void criticalSection() {
if (lock.tryLock()) { // Пытаемся захватить блокировку
try {
System.out.println(Thread.currentThread().getName() + " выполняет критическую секцию");
Thread.sleep(1000); // Эмуляция работы
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock(); // Обязательно освобождаем блокировку
System.out.println(Thread.currentThread().getName() + " завершил работу");
}
} else {
System.out.println(Thread.currentThread().getName() + " не смог захватить блокировку");
}
}
}


Java Learning 👩‍💻

BY Java Learning


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Java_per_month/3142

View MORE
Open in Telegram


Java Learning Telegram | DID YOU KNOW?

Date: |

Telegram announces Anonymous Admins

The cloud-based messaging platform is also adding Anonymous Group Admins feature. As per Telegram, this feature is being introduced for safer protests. As per the Telegram blog post, users can “Toggle Remain Anonymous in Admin rights to enable Batman mode. The anonymized admin will be hidden in the list of group members, and their messages in the chat will be signed with the group name, similar to channel posts.”

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

Java Learning from us


Telegram Java Learning
FROM USA