Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.lock;
- public class CustomLock {
- private boolean isLocked = false;
- public void lock() throws InterruptedException {
- synchronized(this) {
- while(isLocked) wait();
- isLocked = true;
- }
- }
- public void unlock() {
- synchronized(this) {
- if(isLocked) {
- isLocked = false;
- notify();
- }
- }
- }
- }
- package multithreading.lock;
- public class SomeObject {
- private final CustomLock lock = new CustomLock();
- public long count = 0;
- public void inc() throws InterruptedException {
- lock.lock();
- count++;
- lock.unlock();
- }
- }
- package multithreading.lock;
- import java.util.ArrayList;
- import java.util.List;
- public class Client {
- public static void main(String[] args) {
- SomeObject someObject = new SomeObject();
- List<Thread> threads = new ArrayList<>();
- for (int i = 0; i < 500_000; i++) {
- threads.add(new Thread(() -> incTask(someObject), "Thread " + i));
- }
- threads.forEach(Thread::start);
- // Join all threads to complete
- threads.forEach(thread -> {
- try {
- thread.join();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- });
- System.out.println(
- "Value of count is " + someObject.count
- );
- }
- private static void incTask(SomeObject someObject) {
- try {
- someObject.inc();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement