0

When I try to run the below code, the code does not enter into either the block with wait() nor the block with notifyAll(). However, the result of the program is "A B" or "B A". I do not understand what was I missing in the program.

public class threads1 extends Thread {

    static Object obj = new Object();

    public threads1(String str) {
        super(str);
    }

    public void run() {
        try {
            waitforsignal();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void waitforsignal() throws InterruptedException {

        synchronized (obj) {
            System.out.println(Thread.currentThread().getName());
            while (Thread.currentThread().getName() == "A") {
                System.out.println("into wait");
                obj.wait();
            }
            if ((Thread.currentThread().getName() == "B")) {
                System.out.println("had notified");
                obj.notifyAll();
            }
        }
    }

    public static void main(String... strings) throws InterruptedException {
        Thread t1 = new threads1("A");
        Thread t2 = new threads1("B");
        t1.start();
        t2.start();
    }
}
assylias
  • 321,522
  • 82
  • 660
  • 783
smslce
  • 416
  • 1
  • 5
  • 9

1 Answers1

1

It has nothing to do with threads: you are comparing strings with == instead of equals.

Once you have fixed that, note that for thread t1:

Thread.currentThread().getName().equals("A")

will always be true, so your program will never finish...

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • And isn't Thread.currentThread().getName() results in a string. Since string objects created from different references always finally point to same string reference in the pool, why == cannot be used? – smslce Sep 02 '13 at 17:50
  • All strings are compile-time constants here, so because of string interning, I don't think this is the problem. – Ted Hopp Sep 02 '13 at 17:51
  • 1
    @TedHopp, I'm not sure you can make that assumption without knowing the impl of `Thread`. And indeed here, http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java#Thread.getName%28%29, the Thread name is converted into a char array, and then back to a String for `getName()`. – Paul Grime Sep 02 '13 at 17:53
  • @TedHopp Except that Thread, when called with `new Thread(s)`, does not store the string itself, but a `char[]` and a new string is created when `getName` is called. – assylias Sep 02 '13 at 17:53
  • Changed "while" keyword to "if". Now the program is working as I expected. – smslce Sep 02 '13 at 18:05