There are three kinds of actuaries: those who can count, and those who can't.
There are three kinds of actuaries: those who can count, and those who can't.
Piet Souris wrote:hi Forman,
your remarks are mostly correct, but I will go through them to get it 100% correct.
1) Not exactly. A variable that is shared between two or more threads faces the following risks:
a) memory inconsistency. Your processor has, in all likelyhood, more than one core. Every
core has its own piece of memory on-board, and Threads are allowed to store variables
in the memory that belongs to the core that the Thread is running on.
So, you might change a variable, but chances are that this change is not seen by a thread
that has its own copy of that variable. Using 'volatile' ensures that your whole program only
has one place where that variable is stored.
b) thread interference. That is something that has to do with two threads writing at the same
time to the same shared variable, therefore one of the threads results might get lost. The way
to prevent that from happening is to use synchonization in some form.
You change 'flag' in a couple of places: in your main program when the button is clicked,
and in yout thread, where you alternate between flag = 1 and flag = 2.
Usually that will work, but there are no guarantees.
Anyway, this is quite complicated stuff. If you do want to work with threads, and who doesn't,
then a thorough read of the Oracle tutorial about Swing concurrency is essential.
2) yes
3) well, this wasn't actually necessary, I admit. In the constructor of 'RoundPanel' I said
'thread = new Thread(this)'.
and in the 'start' method I needed a reference to this thread. If I had used, in the constructor,
'Thread thread = new Thread(this)', then thread would be a local variable that would not
be available in the 'start' method. That's why I made 'thread' a member variable.
But of course I could have put 'Thread thread = new Thread(this)' into the start method,
and then I would not need 'thread' to be a member variable.
But I like a thread to have a name, so that I can always issue something like 'thread.interrupt()',
in an attempt to finish a thread. But that is not relevant here.
Greetz,
Piet
There are three kinds of actuaries: those who can count, and those who can't.
Piet Souris wrote:Anyway, this is quite complicated stuff. If you do want to work with threads, and who doesn't,
then a thorough read of the Oracle tutorial about Swing concurrency is essential.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
There are three kinds of actuaries: those who can count, and those who can't.
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |