Here\'s my code:
private int count = 0;
public synchronized void increment() {
count++;
}
public void doWork() throws InterruptedException {
Solution 1: Given by fabian. To give a single function incrementAndGet().
Solution 2: A synchronized block instead of synchronized method (if possible):
Complete code would be like:
private int count = 0;
private Object dummyObject = new Object();
public void increment() {
count++;
}
public int getCount() {
return count;
}
public void doWork() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (dummyObject) {
increment();
System.out.println(count + " " + Thread.currentThread().getName());
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (dummyObject) {
increment();
System.out.println(count + " " + Thread.currentThread().getName());
}
}
}
});
t1.start();
t2.start();
}