Graeme Geldenhuys
2017-05-26 14:56:56 UTC
Hi Felipe,
I immediately saw your problem. You are accessing the same data from
more than one thread. That has always been a big NO-NO in any
programming language.
Using the synchronized code blocks to protect the common data or actions
being executed I get this as output.
[threads]$ java FelipeTestThread
Thread 2 finishing
Thread 1 finished. Counted up to 2205390
[threads]$
It works, just like it does when the "volatile" keyword is used.
Attached is the corrected version of your sample application without the
volatile keyword. It is worth noting that using volatile is faster, but
also has its limits (ie: you can't protect a whole block of code or
actions).
But the bottom line is, you tried to access common data from multiple
threads, without trying to protect that data. Not the way to go!
Regards,
Graeme
This simple program never ends if you delete the volatile keyword (I
Yes, I got the same behaviour as you, using Java 1.8 under FreeBSD. ButI immediately saw your problem. You are accessing the same data from
more than one thread. That has always been a big NO-NO in any
programming language.
Using the synchronized code blocks to protect the common data or actions
being executed I get this as output.
[threads]$ java FelipeTestThread
Thread 2 finishing
Thread 1 finished. Counted up to 2205390
[threads]$
It works, just like it does when the "volatile" keyword is used.
Attached is the corrected version of your sample application without the
volatile keyword. It is worth noting that using volatile is faster, but
also has its limits (ie: you can't protect a whole block of code or
actions).
But the bottom line is, you tried to access common data from multiple
threads, without trying to protect that data. Not the way to go!
Regards,
Graeme
--
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/
My public PGP key: http://tinyurl.com/graeme-pgp
fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal
http://fpgui.sourceforge.net/
My public PGP key: http://tinyurl.com/graeme-pgp