Created
April 3, 2012 14:12
-
-
Save raheelahmad/2292304 to your computer and use it in GitHub Desktop.
Joining another thread
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
import java.util.Random; | |
class Runner implements Runnable { | |
public void run() { | |
int c = 0; | |
while (c++ < 10000) | |
if (c % 100 == 0) | |
System.out.println("still at " + c); | |
} | |
} | |
public class Waiter implements Runnable{ | |
int myID; | |
Random gen; | |
Thread wtr; | |
public Waiter(int anID, Thread w) { | |
myID = anID; | |
gen = new Random(); | |
wtr = w; | |
} | |
public void run() { | |
System.out.println("waiting for runner to be done"); | |
try { | |
wtr.join(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Running thread " + myID); | |
int count = 0; | |
while(true) { | |
System.out.println(myID +": At " + count++); | |
try { | |
Thread.sleep(Math.abs(gen.nextInt())%3 * 1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
Thread t1 = new Thread(new Runner()); | |
t1.start(); | |
Thread t2 = new Thread(new Waiter(2, t1)); | |
t2.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment