Created
December 2, 2009 03:12
-
-
Save amygdala/246897 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.inferdata.examples.simplethread; | |
public class MainObj implements Runnable { | |
private int finished_actions; | |
public void run() { | |
System.out.println("starting secondary threads..."); | |
new Thread(new SecondaryThread(this, "action 1")).start(); | |
new Thread(new SecondaryThread(this, "action 2")).start(); | |
new Thread(new SecondaryThread(this, "action 3")).start(); | |
waiting(); | |
System.out.println("finishing MainObj run method"); | |
} | |
synchronized void waiting() { | |
while (finished_actions < 3) { | |
try { | |
System.out.println("in MainObj 'waiting' method, waiting..."); | |
wait(); | |
System.out.println("in MainObj 'waiting' method, got a notification- " + finished_actions + " finished actions."); | |
} | |
catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
synchronized public void processResponse(String action, String resp) { | |
System.out.println("in MainObj.processResponse: got response " + resp + " for action " + action); | |
finished_actions++; | |
notifyAll(); | |
} | |
public static void main(String[] args) { | |
MainObj mt = new MainObj(); | |
new Thread(mt).start(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.inferdata.examples.simplethread; | |
public class SecondaryThread implements Runnable { | |
MainObj callback; | |
String action; | |
SecondaryThread(MainObj cb, String act) { | |
callback = cb; | |
action = act; | |
} | |
public void run() { | |
// generate random sleep time in ms between 0 and 15 seconds | |
int sleeptime = ((int)(Math.random() * 15)) * 1000; | |
System.out.println("pretending to work on " + action + " (" + sleeptime + ")"); | |
try { | |
Thread.sleep(sleeptime); | |
} | |
catch (java.lang.InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("finished " + action); | |
callback.processResponse(action, ""+sleeptime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment