You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public class Main {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
var t1 = new CounterIncrementerThread(counter);
var t2 = new CounterIncrementerThread(counter);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount());
}
}
class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
class CounterIncrementerThread extends Thread {
private Counter counter;
public CounterIncrementerThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
Result of System.out.println(counter.getCount()); will not return 2000
Because count value is updating with multiple thread simulteneusly
Solution to get 2000 always
public synchronized void increment() {
count++;
}
This ensures count is only accessed by one thread at a time
When one thread is accessing count another thread waits because we used synchronized
If we want to use explicit lock then use Lock lock
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
try{
if (lock.tryLock(1L, TimeUnit.MILLISECONDS)) {
count++;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
Seperate read write lock can be used like following
class Counter {
private int count = 0;
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private Lock readLock = lock.readLock();
private Lock writeLock = lock.writeLock();
public void increment() {
try {
writeLock.lock();
count++;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
writeLock.unlock();
}
}
public int getCount() {
try {
readLock.lock();
return count;
} finally {
readLock.unlock();
}
}
}
Inter Thread communication
Use wait to say other thead to wait
Use notify to notify one other thread who want to access shared resource
Use notifyAll to notify all thread that are waiting to access shared resource
Executor service
Instead of creating thread running it and joining it
A better way to run thread is using executor service