Java start and stop

Say I have:

class WriteThread extends Thread { char letter; boolean stop = false; WriteThread(char letter) { this.letter = letter; } public void halt() { stop = true; } public void run() { while(!stop) { System.out.print(letter); } } } 

and

 WriteThread a = new WriteThread('a'); WriteThread b = new WriteThread('b'); a.start(); b.start(); // do some other stuff a.halt(); b.halt(); // (*) 

Are both threads guaranteed when (*) is executed? (by stop, I mean that there will be no more prints after (*))

+4
source share
3 answers

You will need to make the "stop" variable mutable. The thread will end the loop when it sees that vale is true, but there may be output buffering that would confuse the problem.

+4
source

Of course not. It has nothing to do with volatile or not, it's just a multithreading nature.

after you called a.halt (), stream a cannot be given the opportunity to continue execution, and your main stream is b.halt (). After that, thread a can still be in place immediately before your println expression.

Just a simplified version will demonstrate:

 MAIN THREAD THREAD A while (!stop) a.halt() println(...) 

After you called a.halt() , a will still have a chance to continue printing, EVEN stop changes the value of volatile.

To make sure the stream is defined after a certain place, use join ():

 WriteThread a = new WriteThread('a'); WriteThread b = new WriteThread('b'); a.start(); b.start(); // do some other stuff a.halt(); b.halt(); a.join(); b.join(); // a and b are guaranteed to have finished at this point 
+1
source

In addition to being unstable to make your code more thread-safe, you must add synchronized get / set methods for stop and use them (get in the while and set loops) inside the halt method ").

However, you will not have any guarantee that the thread will stop after a “stop”, but you will probably see fewer “fingerprints”.

To get such a guarantee, you should use some kind of thread synchronization mechanism, such as Semaphore , so that the thread calling "a.halt ()" will signal the "a" thread to stop the while loop and stop (inside halt ) until the while loop completes efficiently and frees the semaphore (so that the calling thread continues execution).

0
source

All Articles