/* A "callback function" is a regular function that is executed by a thread. Callbacks are usually used as event handlers. Because the occurrences of event cannot be predicted, threads are used to wait for individual events. Example of events include completion of IO or completion of thread. When an event occurs, the thread responsible for it would call the corresponding callback function. Note that the use of callbacks usually replaces the use of "join". Since The code to be executed upon thread completion is to be executed by the thread itself. */ // requires plaingui.java import java.io.*; class iothread implements Runnable { master parent; // pointer to parent class, needed for callbacks public iothread(master owner) {parent=owner;} public void run() { try { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); while (true) { System.out.println("waiting for your input: "); String s = br.readLine(); // make callback parent.handleio(s); } } catch(Exception e) {System.out.println(e);} } } // iothread class slowthread implements Runnable { int i; master parent; public slowthread(master m, int d) {parent=m; i=d;} public void run() { try { System.out.println("wait for "+i+" to wake up"); Thread.sleep(i*1000); // make callback parent.handleslow(i); } catch (Exception e) {System.out.println(e);} } }//slowthread class master { plaingui gui = new plaingui(20,20,300,400); public master() { Thread t1 = new Thread(new iothread(this)); Thread t2 = new Thread(new slowthread(this,4)); Thread t3 = new Thread(new slowthread(this,8)); t1.start(); t2.start(); t3.start(); gui.outputarea.append("MASTER OUTPUT: threads have started...\n"); } // Callback functions: public void handleio(String s) { gui.outputarea.append("what am I supposed to do with "+s+"?\n"); } public void handleslow(int i) { gui.outputarea.append("so "+i+" has finally finished!\n"); } } //master public class callbacks { public static void main(String[] args) { master m = new master(); } }