This discussion is archived
3 Replies Latest reply: May 11, 2012 4:24 PM by EJP RSS

Block thread until callback method has been called by other thread

936817 Newbie
Currently Being Moderated
Hi All,

Please can you advise best way to block or suspend an application thread, until another thread has called a method in the application's class.

Thank you for your time and help,
Best regards,
James
-----
public class ThreadTester {
public static void main(String[] args) {
new ThreadTester().application();
}

public void application() {
for (int i=0; i<10; i++) {
Thread t = new Thread(new Process(this, i));
t.start();
     /* wait here until serviceSearchCompleted() has been called by Process */
}
}

public void serviceSearchCompleted(int number) {
System.out.println("Completed search " + number);
     /* notify application() method to continue beyond 'waiting point' */
}
}



class Process implements Runnable {
private ThreadTester threadTester;
private int number;

public Process(ThreadTester threadTester, int number) {
this.threadTester = threadTester;
this.number = number;
}

public void run() {
startSearchServices();
}

private void startSearchServices() {
System.out.println("Started search " + number);
try {
Thread.sleep(1000); //...seaching...
} catch (InterruptedException ie) {}
threadTester.serviceSearchCompleted(number);
}
}

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points