I am new to multithreading and although I read about multithreading, I thought about writing this fancy multithreaded 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 split between two threads. After starting the threads, I need to do the following. I want Thread2 to wait for Thread1 to increment the counter of the Counter object by 1. Once this is done, then Thread 1 tells thread2, and then Thread1 starts to wait until thread2 decreases the value by 1. Then thread2 starts and decreases the value by 1 and informs thread1 again, and then thread2 starts waiting for thread1. Repeat this process several times.
How can i achieve this. Thank you very much in advance.
I did 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");
}
}
}