since this is my first question ever on stackoverflow, I will try to explain it as good as possible.
I am sorry if this is a duplicate question, but I spent a lot of time searching and couldn't find an answer to this. Since i started learning Threads not so long ago I came upon an obstacle now:D I want to code a NOT thread safe method, using two threads to increment and decrement an integer at the same time.
so my code so far is this .. sadly is not working and i don't know why
public class ThreadFunctions {
private int counter = 0;
private boolean command = false;
public synchronized void changeNumber(boolean command){
this.command = command;
synchronized (this) {
if(command){
counter++;
}else{
counter--;
}
}
}
public synchronized int getCounter(){
return this.counter;
}
}
And that's the class I use to test it.
public class Demo{
public static void main(String[] args){
final ThreadFunctions o = new ThreadFunctions();
new Thread(new Runnable() {
@Override
public void run() {
while(o.getCounter() < 100){
o.changeNumber(true);
System.out.println("Thread: " + Thread.currentThread().getId() + " counter: "+o.getCounter());
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(o.getCounter() > -100){
o.changeNumber(false);
System.out.println("Thread: " + Thread.currentThread().getId() + " counter: "+ o.getCounter());
}
}
}).start();
}
}
and the results are something like this ...
Thread: 10 counter: 5
Thread: 10 counter: 6
Thread: 10 counter: 7
Thread: 10 counter: 8
Thread: 10 counter: 9
Thread: 11 counter: 8
Thread: 10 counter: 9
Thread: 10 counter: 10
Thread: 10 counter: 11
Thread: 10 counter: 11
Thread: 10 counter: 12
Thread: 10 counter: 13
Thread: 11 counter: 13
etc..
So as u can see the threads are still not synchronised and i don't understand why:(