cow12331
cow12331

Reputation: 245

How to terminate a running loop in java?

Program A:

    public void startThreadPool2(boolean flag) {
    while(flag) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                System.out.println("running");
            }
        };
        service.execute(run);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Program B:

    public static void main(String[] args) {
    SentimentAnalyse sentimentAnalyse = SentimentAnalyse.getInstance();
    sentimentAnalyse.startThreadPool2(true);
}

Program C:

public static void main(String[] args) {
    //how to stop the while loop
}

A while loop keep running and I don't know how to stop it in another program.

//update Your ways maybe all works, I find my singleton don't work due to eclipse use different class loader in different program.

Upvotes: 0

Views: 777

Answers (1)

Michael
Michael

Reputation: 815

Store the flag in the SentimentAnalyse and provide a setter for it! In porgram c (what ever this is) you need a reference to the instance of SentimentAnalyse, that you've created in program b. Stop the loop in programm a by calling its setter with false from program c

Upvotes: 1

Related Questions