Java thread run
I have c开发者_如何学Goode like this
boolean start = false;
ThreadX a = new ThreadX();
a.start();
start = true;
Class ThreadX extends Thread {
public void run() {
while (start == true) {
...
}
}
}
Is there a problem with this code? I have executed this and did not see any issue just wanted to get a hang whether the thread will start and never execute start = true
There are two problems:
- Firstly the thread could in theory start before
start
is ever set to true, and thus terminate immediately. - Secondly the thread could in theory start after
start
is set to true, but never set the value ofstart
change (assuming it's being set to false somewhere in the original thread) due to a lack of memory barriers. Either make the variable volatile, use locks, or use one of theAtomicXXX
types in java.util.concurrent.atomic, e.g.AtomicBoolean
.
Also for good practice you should implement Runnable
instead of extening Thread
- you don't want to change the fundamental behaviour of a thread, you just want to provide it a task. (The fact you can extend thread to do this is a design flaw IMO.)
Yes, there is a problem.
Assuming that start
is a local variable, this code will not even compile, since all local variables that are used in inner classes have to be final
.
Assuming that start
is a field of some class. Then the field must be declared volatile
, otherwise it is not guaranteed that if one thread changes the variable, the other threads will see that change.
It depends if start
becomes true before or after run()
begins. I say "it depends" because there is no guarantee by the JVM that either will be the case. This is, of course, assuming that start
is within scope of the instance of your thread.
with this it is not guaranteed that the loop will ever enter:
if the thread is started and the current thread (the thread starting the other one) is interrupted so the other thread can run the while condition will be false and the run will exit
on the other hand if the current thread is not interrupted and set start to true the loop will enter
this is known as a race condition
The thread will start, but might exit immedietly, exit later, or run forever:
Scenario 1 - run forever before thread run() enters, start is updated to true and the jvm decides to write it to the memory so the created thread will see it as true and will never terminate.
Scenario 2 - exit immediately before run() starts the start is updated to true but the jvm don't update physical memory (no membar), then run continues and sees false, and will terminate, or the run() and the loop runs for the first before start=true is run.
Scenario 3 - exit at some point before run() or after run() start is updated but the jvm updates the physical memory at some point after run do a number of iterations.
精彩评论