I have a thread sleep problem. Inside the thread run method i have a synchronized block, and a sleep time. Each thread increments or decrements the shared class "value" in 5 units, and then sleeps.
public class borr {
public static void main(String[] args) {
int times=5;
int sleeptime=1000;
int initial=50;
Shared shared = new Shared(initial);
ThreadClass tIncrement = new ThreadClass(shared,times,sleeptime,true);
ThreadClass tDecrement = new ThreadClass(shared,times,sleeptime,false);
tIncrement.start();
tDecrement.start();
}
}
class Shared{
int value=0;
public Shared(int value) {
super();
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
class ThreadClass extends Thread{
Shared shared;
int times=0;
int sleeptime=0;
boolean inc;
public ThreadClass(Shared shared, int times, int sleeptime, boolean inc) {
super();
this.shared = shared;
this.times = times;
this.sleeptime = sleeptime;
this.inc = inc;
}
public void run() {
int aux;
if(inc) {
for(int i=0;i<times;i++) {
synchronized(shared) {
aux=shared.getValue()+1;
shared.setValue(aux);
System.out.println("Increment, new value"+shared.getValue());
try {
Thread.sleep(sleeptime);
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
else {
for(int i=0;i<times;i++) {
synchronized(shared) {
aux=shared.getValue()-1;
shared.setValue(aux);
System.out.println("Decrement, new value"+shared.getValue());
try {
Thread.sleep(sleeptime);
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
}
But if I move the Thread.sleep
out of the synchronized
block, like this, the output is increment, decrement, increment, decrement. When it stops sleeping and starts a new iteration of the loop, shouldn't the other thread try to enter? instead, it continues looping until that thread is finished:
for(int i=0;i<times;i++) {
synchronized(shared) {
aux=shared.getValue()-1;
shared.setValue(aux);
System.out.println("Decrement, new value"+shared.getValue());
}
try {
Thread.sleep(sleeptime);
}catch(Exception e) {
e.printStackTrace();
}
}