Hi everyone,

Consider below code,

package thread;

public class Noti5 extends Thread{

    Calc c;
    Noti5(Calc calc){
        c = calc;
    }

    public void run(){
        synchronized(c){
         try{
             System.out.println("waiting for calculation..");

             c.wait();
         }catch(Exception e){}
         System.out.println("Total is.."+c.total);
        }
    }

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

        Calc calculator = new Calc();
        new Noti5(calculator).start();new Noti5(calculator).join();
        new Noti5(calculator).start();
        new Noti5(calculator).start();
        calculator.start();

    }


}
class Calc extends Thread{
    int total;
    public void run(){
        synchronized(this){
         for(int i=0;i<10;i++){
             total += i;
         }
         notify();
        }
    }
}

1.if we didnt use "c.wait" & "notify" in above code then it produces different results.
what is the use of this both?
i have basic understanding of both,but couldnt find out satisfactory answer.

2.can we use notify() without wait() or wait() without notify()?

3.what happens if we call notify() first and then code reads wait()?

Kindly correct me if im wrong.

Thanks in advance.

it's point is to produce the correct results, as you said: if you don't call those methods, it produces different results.

your code is synchronized, that is why it will always return the same (expected) result.

as for what those method calls do, I suggest you take a look at the api's:
notify
wait

I don't know where you got this code, but a few remarks about it:

public class Noti5 extends Thread{

unless you plan to change the default behaviour of the Thread class, you should not do this (and in at least 98% of Thread classes out there, you don't want to change anything about it), but create Threads by implementing Runnable, rather than extending Thread.

catch(Exception e){}

try and learn to learn from the beginning never to do this. your application might crash, and you would be none the wiser. even if you don't want to actually handle the exception, you should at the very least put some logging or a basic error message there, so that at least you'll be informed of what might go wrong.
the best way would be to include a stacktrace printed.

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

even though I understand the ease of using this when just writing small example classes and programs, I never recommend it. a try and catch within the main method would handle the exception just as well, but it would allow the developer to write his code in such a way, that the exception might occur without automatically terminating the application.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.