Block thread until callback method has been called by other thread
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
Code:
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);
}
}
Re: Block thread until callback method has been called by other thread
There are a great many ways. Set a flag and wait for it to be set by the Runnable, use Thread.join(), create a Semaphore...
Re: Block thread until callback method has been called by other thread
Thank you for your reply. I have managed to RESOLVE this problem using the code below.
Code:
public class ThreadTester {
private Object synchObj = new Object();
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();
synchronized (synchObj) {
try { synchObj.wait(); } catch (InterruptedException ie) {}
}
}
}
public void serviceSearchCompleted(int number) {
System.out.println("Completed search " + number);
synchronized (synchObj) {
synchObj.notify();
}
}
}
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);
}
}
Re: Block thread until callback method has been called by other thread
Cross posted at Block thread until callback method has been called by other thread
Be sure to tell the other forums that you have solved this.
Re: Block thread until callback method has been called by other thread