简体   繁体   中英

Java running and stopping threads

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 to stop when (*) is executed? (by stop I mean that there will not be anymore prints after (*) )

You would need to make the 'stop' variable volatile. The thread will cease looping when it sees that vale is true, but there may be output buffering which would confuse the issue.

Of course not. It has nothing to do with volatile or not, it is simply the nature of multi-threading.

after you called a.halt(), thread a may not be granted any chance to continue execute, and your main thread do b.halt(). After that, thread a may still be at the spot just before your println statement.

Just a simplified version will demonstrate:

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

After you called a.halt() , a will still have chance to continue printing, EVEN stop variable is volatile.

In order to make sure a thread finished after certain spot, please 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

Besides making the "stop" variable volatile, to make your code more "thread-safe", you should add synchronized get/set methods for "stop" and use them ("get" in the while loop and "set" inside the "halt" method).

Still, you will have no guarantee that the thread will stop after "halt", but you probably will see less "prints".

To have such guarantee, you must use some sort of "thread synchronization" mechanism, such as a Semaphore , in a way that the thread calling "a.halt()" signals the "a" thread to stops the "while" loop and stops (inside halt) until the "while" loop effectively ends and "release" the semaphore (so the calling thread continues its execution).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM