Hi Charles
The problem with your code is not a bug, it's just how thread are scheduled
by the underliying VM.
Your code running on Linux is unblocking (notifyAll) before, there is any
thing waiting (wait) on the lock. The run method in SThread run to the
while loop, before the XThread run starts. Maybe adding a Thread.yeild()
just after the new Socket() would work.
Below is the output with the changes I made to your code, which I ran on
Linux JDK 1.1.6v5.
Unblocking pause()
Before notifyAll
After notifyAll
Before wait
Hope this helps.
Robert Fitzsimons
> import java.net.*;
> import java.util.Date;
>
> public class STest {
> public static void main(String[] param) {
> if (param.length != 1) {
> System.out.println("Usage: java STest <host>");
> System.exit(1);
> }
>
> SThread t = new SThread(param[0]);
> XThread x = new XThread(t);
> try {
> t.start();
> x.start();
> x.join();
> System.out.println("XThread completed. Socket should be closed");
> } catch(Exception e) {
> e.printStackTrace();
> }
> }
> }
>
> class XThread extends Thread {
> private SThread st;
>
> public XThread(SThread st) { this.st = st; }
>
> public void run() {
> try {
> st.pause();
> System.out.println("XThread sleeping for a little bit.\t" +
> new Date());
> sleep(5000);
> System.out.println("XThread awake.\t\t\t" + new Date());
> st.s.close();
> } catch(Exception e) {
> e.printStackTrace();
> }
> }
> }
>
> class SThread extends Thread {
> private String host;
> public Socket s;
> public SThread(String host) { this.host = host; }
>
> public void run() {
> try {
> // Open a telnet socket to the host passed on the command line
> s = new Socket(host, 23);
>
> System.out.println("Unblocking pause()");
System.out.println("Before notifyAll");
> synchronized(this) { notifyAll(); }
System.out.println("After notifyAll");
>
> while(true) {
> s.getInputStream().read();
> }
> } catch(Exception e) {
> e.printStackTrace();
> }
> }
>
> public synchronized void pause() {
System.out.println("Before wait");
> try { wait(); } catch(Exception e) { e.printStackTrace(); }
System.out.println("After wait");
> }
> }