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?

  • The question is not very clear. Add a run counter before stop() , and check whether it has reached 10 in the loop condition. - Nofate

1 answer 1

I solved my question myself. It was necessary to create an object for monitoring

 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++) { synchronized(m1.obj) { m1.setFlag(true); m1.obj.wait(); } } } } 

And class MyClass

 public class MyClass implements Runnable { private Boolean flag = false; public final Object obj = new Object(); public void run() { while (true) { if (flag) { synchronized(obj) { try { stop(); } catch (InterruptedException e) { e.printStackTrace(); } flag = false; obj.notify(); } } } } public void stop() throws InterruptedException { Thread.sleep(1000); System.out.println("Sleeeep"); } public void setFlag(Boolean flag) { this.flag = flag; } } 
  • It was enough to declare the flag variable as volatile . - a_gura
  • and nothing would have changed - MrGarison
  • Oh yes. Misunderstood the condition of the problem. Anyway - a_gura