Javamex

Java discussion forum to accompany the Javamex web site.

Does anybody know why in the following program:

- T1 started first but goes into a sleep which allows T2 to run.
- T2 synchronizes on T1 but goes into a wait().
- T1 continues, synchronizes on itself then calls notify(), releases the lock and does a read from command line.

-At this point T2 should wake up but it never does?

I found the only way for T2 to wait up is to have T1 calls notify() twice or calls notifyAlll(),
or done with the run() method which it dies.  Why?

import java.io.*;

public class ThreadTest1 {

    private static class T1 extends Thread {

        private T2 t2;

        public void setT2(T2 t2) {
            this.t2 = t2;
        }

        public void run() {
            try {
                sleep(1000);   // always give T2 a chance to run first
                synchronized (this) {
                    System.out.println("Thread1 notifies");
                    this.notify();
                    System.out.println("Thread1 done notify");
                    // this.wait();
                }
                System.out.println("Thread1 done synchronized... enter a number.");
                int k = System.in.read();
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    private static class T2 extends Thread {

        private final T1 t1;

        public T2(T1 t1) {
            this.t1 = t1;
        }

        public void run() {

            try {
                synchronized (t1) {
                    System.out.println("Thread2 waits on t1");
                    t1.wait();
                    System.out.println("Thread2 done waiting for t1");
                }

                synchronized (this) {
                    System.out.println("Thread2 notifies");
                    this.notify();
                    System.out.println("Thread2 done notify");
                }
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {

        T1 t1 = new T1();
        T2 t2 = new T2(t1);
        t1.setT2(t2);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

Views: 65

Reply to This

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service