Prasanth;
Both our last posts are timed at 12:08; my previous post referred to your 11:45. About your 12:08: Using <code>isAlive()</code> is a good idea (one of us should have tried that before, Rahul), but I have a couple of questions about your implementation of it.
First, why are you saying <code>!isAlive()</code>? Seems like you'd want to print "Alive" if the
test returned <code>true</code>, but your code prints "Alive" if <code>isAlive()</code> returns <code>false</code>. It's confusing.
Second, and more importantly, what if a time slice occurs after the test but before the call to start? The thread could be alive at the time you check its liveness but dead before the other one gets going. I swiped your idea and wrote this little thing; it addresses that problem by placing the liveness check in <code>run()</code>.<pre><code>
class Demo2 {
public static void main(
String[] args) {
try {
demo1 xx = new demo1();
Thread t = new Thread( xx, "ThreadT" );
Thread u = new Thread( t, "ThreadU" );
xx.setThreadT( t );
t.start();
if (args.length > 0 && args[0].equals( "delay" )) {
for (int i = 0; i < 100000; i++);
}
u.start();
} catch (Exception e) {
System.out.println(e);
}
}
}
class demo1 implements Runnable {
private Thread threadT = null;
public void setThreadT( Thread t ) {
threadT = t;
}
public void run() {
if (threadT != null && Thread.currentThread() != threadT) {
if (threadT.isAlive()) {
System.out.println( threadT.getName() + " is alive" );
} else {
System.out.println( threadT.getName() + " is not alive" );
}
}
System.out.println( Thread.currentThread().getName() + " in run");
}
}</code></pre>
It's kind of a kludge, I know. Given the check that says "do the test only if I'm not threadT", only thread <code>u</code> will make the liveness check. If on any given execution you see a "ThreadU in run" output line, you'll also see a "ThreadT is alive" line. This shows that <code>t</code> is alive whenever <code>u</code> runs. This isn't a complete proof because we never get the negative check (I did one like that, but it got too messy), but it at least supports my point. (At least, this is the behavior I get.)
If your computer, like mine, needs some help to actually let one thread die before the other runs, say "java Demo2 delay" on the command line and the time-waster will run in between the <code>start()</code> calls.
jply
[This message has been edited by Jerry Pulley (edited October 03, 2000).]