I have such a class
public class MyClass implements Runnable { private Boolean flag = false; public void run() { while (true) { if (flag) { try { stop(); } catch (InterruptedException e) { e.printStackTrace(); } flag = false; } } } public void stop() throws InterruptedException { Thread.sleep(1000); System.out.println("Sleeeep"); } public void setFlag(Boolean flag) { this.flag = flag; } }
And such a class with the main method
public class Main { public static void main (String[] args) throws IOException, InterruptedException { MyClass m1 = new MyClass(); Thread t1 = new Thread(m1); t1.start(); for (int i = 0; i < 10; i++) { m1.setFlag(true); } } }
How to make the stop
method of class MyClass
run 10 times?
run
counter beforestop()
, and check whether it has reached 10 in the loop condition. - Nofate ♦