I am new to multi-threading and While I am reading about multi threading, thought of writing this fancy multi-threading code to do the following.
My counter class is as follows.
class Counter {
private int c = 0;
public void increment() {
System.out.println("increment value: "+c);
c++;
}
public void decrement() {
c--;
System.out.println("decrement value: "+c);
}
public int value() {
return c;
}
}
This Counter object is shared between two threads. Once threads are started, I need to do the following. I want Thread2 to wait until the Thread1 increments the count of the Counter object by 1. Once this is done, Then Thread 1 informs thread2 and then Thread1 starts waiting for thread2 to decrement value by 1. Then thread2 starts and decrements value by 1 and informs thread1 again and then thread2 start waiting for thread1. Repeat this process for few times.
How can I achieve this. Many thanks in advance.
I have done the following.
public class ConcurrencyExample {
private static Counter counter;
private static DecrementCount t1;
private static IncrementCount t2;
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(new IncrementCount(counter));
t1.start();
Thread t2 = new Thread(new DecrementCount(counter));
t2.start();
}
}
public class DecrementCount implements Runnable {
private static Counter counter;
public DecrementCount(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.decrement();
System.out.println("decreamented");
}
}
}
public class IncrementCount implements Runnable {
private static Counter counter;
public IncrementCount(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
System.out.println("Incremented");
}
}
}
IncrementCount
should callincrement()
, right? – Tomasz Nurkiewicz