Printing a sequence of numbers using two alternating threads

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite












I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?



Main Class



public class MyMain 
public static void main(String args)
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);

thread1.setName("t1");
thread2.setName("t2");

thread1.start();
thread2.start();





Thread Class



public class MyThread1 implements Runnable
int i = 0;
@Override
public synchronized void run()
while(i<10)

if(i%2==0)

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();

catch(Exception e) e.printStackTrace();
else

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();
catch(Exception e) e.printStackTrace();






Can there be a better usage of wait() and notify() instead of using it in both the if conditions?







share|improve this question





















  • Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting
    – Ludisposed
    Apr 4 at 10:17

















up vote
1
down vote

favorite












I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?



Main Class



public class MyMain 
public static void main(String args)
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);

thread1.setName("t1");
thread2.setName("t2");

thread1.start();
thread2.start();





Thread Class



public class MyThread1 implements Runnable
int i = 0;
@Override
public synchronized void run()
while(i<10)

if(i%2==0)

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();

catch(Exception e) e.printStackTrace();
else

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();
catch(Exception e) e.printStackTrace();






Can there be a better usage of wait() and notify() instead of using it in both the if conditions?







share|improve this question





















  • Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting
    – Ludisposed
    Apr 4 at 10:17













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?



Main Class



public class MyMain 
public static void main(String args)
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);

thread1.setName("t1");
thread2.setName("t2");

thread1.start();
thread2.start();





Thread Class



public class MyThread1 implements Runnable
int i = 0;
@Override
public synchronized void run()
while(i<10)

if(i%2==0)

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();

catch(Exception e) e.printStackTrace();
else

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();
catch(Exception e) e.printStackTrace();






Can there be a better usage of wait() and notify() instead of using it in both the if conditions?







share|improve this question













I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?



Main Class



public class MyMain 
public static void main(String args)
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);

thread1.setName("t1");
thread2.setName("t2");

thread1.start();
thread2.start();





Thread Class



public class MyThread1 implements Runnable
int i = 0;
@Override
public synchronized void run()
while(i<10)

if(i%2==0)

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();

catch(Exception e) e.printStackTrace();
else

try
notify();
System.out.println(Thread.currentThread().getName()+" prints "+i);
i++;
wait();
catch(Exception e) e.printStackTrace();






Can there be a better usage of wait() and notify() instead of using it in both the if conditions?









share|improve this question












share|improve this question




share|improve this question








edited Apr 4 at 16:57









200_success

123k14142399




123k14142399









asked Apr 4 at 9:47









dexter87

61




61











  • Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting
    – Ludisposed
    Apr 4 at 10:17

















  • Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting
    – Ludisposed
    Apr 4 at 10:17
















Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting
– Ludisposed
Apr 4 at 10:17





Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting
– Ludisposed
Apr 4 at 10:17











1 Answer
1






active

oldest

votes

















up vote
3
down vote















I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:



public synchronized void run() 
while (i < 10)
try
notify();
System.out.println(Thread.currentThread().getName() + " prints " + i);
i++;
wait();
catch (Exception e)
e.printStackTrace();





Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.



Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.






share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191234%2fprinting-a-sequence-of-numbers-using-two-alternating-threads%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote















    I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:



    public synchronized void run() 
    while (i < 10)
    try
    notify();
    System.out.println(Thread.currentThread().getName() + " prints " + i);
    i++;
    wait();
    catch (Exception e)
    e.printStackTrace();





    Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.



    Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.






    share|improve this answer

























      up vote
      3
      down vote















      I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:



      public synchronized void run() 
      while (i < 10)
      try
      notify();
      System.out.println(Thread.currentThread().getName() + " prints " + i);
      i++;
      wait();
      catch (Exception e)
      e.printStackTrace();





      Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.



      Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.






      share|improve this answer























        up vote
        3
        down vote










        up vote
        3
        down vote











        I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:



        public synchronized void run() 
        while (i < 10)
        try
        notify();
        System.out.println(Thread.currentThread().getName() + " prints " + i);
        i++;
        wait();
        catch (Exception e)
        e.printStackTrace();





        Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.



        Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.






        share|improve this answer















        I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:



        public synchronized void run() 
        while (i < 10)
        try
        notify();
        System.out.println(Thread.currentThread().getName() + " prints " + i);
        i++;
        wait();
        catch (Exception e)
        e.printStackTrace();





        Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.



        Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.







        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Apr 4 at 10:43









        Stingy

        1,888212




        1,888212






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f191234%2fprinting-a-sequence-of-numbers-using-two-alternating-threads%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?