This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Threads and Synchronization and the fly likes How to interrupt or stop the threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply locked New topic

How to interrupt or stop the threads

Ja King

Joined: May 15, 2009
Posts: 28
I am running multiple threads (Assume Thread1,Thread2,Thread3) for doing single operation.If any one of the threads done that operation(Thread2) then the remaining threads(Thread1,Thread3) will stop suddenly.

please guide me how to kill that remaining threads suddenly.I don't know how to stop it suddenly.(Marked in red color).


import java.util.Random;

class RandomGenerator implements Runnable{

public void run(){

public void random(){
Random random = new Random();
int randomNum = 0;
randomNum = random.nextInt(100);
}while(!(randomNum == 5));
System.out.println(Thread.currentThread() + " identified the random number : " + randomNum);

public class TestThread1 {
public static void main(String args[]){
RandomGenerator rg = new RandomGenerator();
Thread th1 = new Thread(rg,"Thread1");
Thread th2 = new Thread(rg,"Thread2");
Thread th3 = new Thread(rg,"Thread3");


Actual output :
Thread[Thread2,5,main] identified the random number : 5
Thread[Thread1,5,main] identified the random number : 5
Thread[Thread3,5,main] identified the random number : 5

Expected output:
Thread[Thread2,5,main] identified the random number : 5
Thread1 killed
Thread2 Killed

Note: Don't use boolean variable to check continuously.
Steve Luke

Joined: Jan 28, 2003
Posts: 4180

This is a double post from this previous thread: If you could please CarefullyChooseOneForum so people don't duplicate effort. Since there is already a response in the other thread, I suggest we keep the conversation running there. If you would like we can move that thread to this forum. In the mean time I will lock this one so we don't have two parallel conversations running.

wood burning stoves
subject: How to interrupt or stop the threads