// this is just an example to better understand. I would like to understand if it is necessary or not to lock I don't know if this example is suitable for what I want to understand .............................................................................................................................................................................................
class Counter{
int counter;
public ReentrantLock lock=new ReentrantLock();
//if the variable is visible to more Threads all readings and writes must be Thread-safe?
public void incr() {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
}
public void decr() {
lock.lock();
try {
counter--;
} finally {
lock.unlock();
}
}
//must have Lock
public int getincr() {
return counter;
}
}
//these are the Thread
public class Worker extends Thread {
private Counter c;
public Worker (Counter c) {
this.c=c;
}
enter code here
public void run() {
System.out.println(Thread.currentThread().getName());
for(int i=1;i<=10;i++) {
c.incr(); System.out.println(c.getincr());//this is the method
c.decr(); System.out.println(c.getincr());
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Main
public class Test {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Counter c=new Counter();
Worker[] threads = new Worker[100];
for(int i=0;i<100;i++) {
threads[i]=new Worker(c);
threads[i].start();
//threads[i].join();
}
}
}