Alternate threads to print even and odd numbers

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
4
down vote

favorite












I have written the following piece of code to have two threads printing odd and even numbers alternatively. I know this is a common question but I wanted to get this reviewed and understand if it is right or wrong. If wrong, can this be tweaked slightly to get desired result or the approach itself is wrong. Thanks for help.



public class ThreadTest implements Runnable

private static int counter = 1;
private static final Object lock = new Object();

public static void main(String args)
// TODO Auto-generated method stub

Thread t1 = new Thread(new ThreadTest(), "arunabh");
t1.start();
Thread t2 = new Thread(new ThreadTest(), "hejib");
t2.start();




@Override
public void run()
while (counter<=100)
synchronized (lock)
if (counter % 2 == 0)
System.out.println(counter +" Written By even Thread-"+ Thread.currentThread().getName());
counter++;
try
lock.notify();
lock.wait();

catch (InterruptedException e)
e.printStackTrace();


else if (counter % 2 == 1)
System.out.println(counter +" Written By odd Thread-"+ Thread.currentThread().getName());
counter++;

try
lock.notify();
lock.wait();

catch (InterruptedException e)
e.printStackTrace();













share|improve this question



























    up vote
    4
    down vote

    favorite












    I have written the following piece of code to have two threads printing odd and even numbers alternatively. I know this is a common question but I wanted to get this reviewed and understand if it is right or wrong. If wrong, can this be tweaked slightly to get desired result or the approach itself is wrong. Thanks for help.



    public class ThreadTest implements Runnable

    private static int counter = 1;
    private static final Object lock = new Object();

    public static void main(String args)
    // TODO Auto-generated method stub

    Thread t1 = new Thread(new ThreadTest(), "arunabh");
    t1.start();
    Thread t2 = new Thread(new ThreadTest(), "hejib");
    t2.start();




    @Override
    public void run()
    while (counter<=100)
    synchronized (lock)
    if (counter % 2 == 0)
    System.out.println(counter +" Written By even Thread-"+ Thread.currentThread().getName());
    counter++;
    try
    lock.notify();
    lock.wait();

    catch (InterruptedException e)
    e.printStackTrace();


    else if (counter % 2 == 1)
    System.out.println(counter +" Written By odd Thread-"+ Thread.currentThread().getName());
    counter++;

    try
    lock.notify();
    lock.wait();

    catch (InterruptedException e)
    e.printStackTrace();













    share|improve this question























      up vote
      4
      down vote

      favorite









      up vote
      4
      down vote

      favorite











      I have written the following piece of code to have two threads printing odd and even numbers alternatively. I know this is a common question but I wanted to get this reviewed and understand if it is right or wrong. If wrong, can this be tweaked slightly to get desired result or the approach itself is wrong. Thanks for help.



      public class ThreadTest implements Runnable

      private static int counter = 1;
      private static final Object lock = new Object();

      public static void main(String args)
      // TODO Auto-generated method stub

      Thread t1 = new Thread(new ThreadTest(), "arunabh");
      t1.start();
      Thread t2 = new Thread(new ThreadTest(), "hejib");
      t2.start();




      @Override
      public void run()
      while (counter<=100)
      synchronized (lock)
      if (counter % 2 == 0)
      System.out.println(counter +" Written By even Thread-"+ Thread.currentThread().getName());
      counter++;
      try
      lock.notify();
      lock.wait();

      catch (InterruptedException e)
      e.printStackTrace();


      else if (counter % 2 == 1)
      System.out.println(counter +" Written By odd Thread-"+ Thread.currentThread().getName());
      counter++;

      try
      lock.notify();
      lock.wait();

      catch (InterruptedException e)
      e.printStackTrace();













      share|improve this question













      I have written the following piece of code to have two threads printing odd and even numbers alternatively. I know this is a common question but I wanted to get this reviewed and understand if it is right or wrong. If wrong, can this be tweaked slightly to get desired result or the approach itself is wrong. Thanks for help.



      public class ThreadTest implements Runnable

      private static int counter = 1;
      private static final Object lock = new Object();

      public static void main(String args)
      // TODO Auto-generated method stub

      Thread t1 = new Thread(new ThreadTest(), "arunabh");
      t1.start();
      Thread t2 = new Thread(new ThreadTest(), "hejib");
      t2.start();




      @Override
      public void run()
      while (counter<=100)
      synchronized (lock)
      if (counter % 2 == 0)
      System.out.println(counter +" Written By even Thread-"+ Thread.currentThread().getName());
      counter++;
      try
      lock.notify();
      lock.wait();

      catch (InterruptedException e)
      e.printStackTrace();


      else if (counter % 2 == 1)
      System.out.println(counter +" Written By odd Thread-"+ Thread.currentThread().getName());
      counter++;

      try
      lock.notify();
      lock.wait();

      catch (InterruptedException e)
      e.printStackTrace();















      share|improve this question












      share|improve this question




      share|improve this question








      edited Jan 8 at 8:08









      Martin R

      14.1k12257




      14.1k12257









      asked Jan 8 at 7:59









      Arunabh

      211




      211




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          I have two comments of the tweaking kind:



          1) any variable that is shared between threads has to be volatile. this is true even for static variables that have one value throughout the JVM (actually it is per class loader but this is irrelevant here). The reason for that is that threads can locally cache the value of variables. volatile variables force the thread to read the global value each time.



          You might also want to take a look at AtomicInteger which is an int that is guaranteed to be incremented synchronously and that has the same value for all running threads.



          2) while synchronized will work, Java concurrency package has several Lock mechanisms that allow for better control over the synchronization process. of relevancy here are ReentrantLock, ReadWriteLock.






          share|improve this answer





















          • So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
            – Arunabh
            Jan 8 at 9:27










          • I don't know about this specific scenario.
            – Sharon Ben Asher
            Jan 8 at 9:49










          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%2f184559%2falternate-threads-to-print-even-and-odd-numbers%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
          0
          down vote













          I have two comments of the tweaking kind:



          1) any variable that is shared between threads has to be volatile. this is true even for static variables that have one value throughout the JVM (actually it is per class loader but this is irrelevant here). The reason for that is that threads can locally cache the value of variables. volatile variables force the thread to read the global value each time.



          You might also want to take a look at AtomicInteger which is an int that is guaranteed to be incremented synchronously and that has the same value for all running threads.



          2) while synchronized will work, Java concurrency package has several Lock mechanisms that allow for better control over the synchronization process. of relevancy here are ReentrantLock, ReadWriteLock.






          share|improve this answer





















          • So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
            – Arunabh
            Jan 8 at 9:27










          • I don't know about this specific scenario.
            – Sharon Ben Asher
            Jan 8 at 9:49














          up vote
          0
          down vote













          I have two comments of the tweaking kind:



          1) any variable that is shared between threads has to be volatile. this is true even for static variables that have one value throughout the JVM (actually it is per class loader but this is irrelevant here). The reason for that is that threads can locally cache the value of variables. volatile variables force the thread to read the global value each time.



          You might also want to take a look at AtomicInteger which is an int that is guaranteed to be incremented synchronously and that has the same value for all running threads.



          2) while synchronized will work, Java concurrency package has several Lock mechanisms that allow for better control over the synchronization process. of relevancy here are ReentrantLock, ReadWriteLock.






          share|improve this answer





















          • So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
            – Arunabh
            Jan 8 at 9:27










          • I don't know about this specific scenario.
            – Sharon Ben Asher
            Jan 8 at 9:49












          up vote
          0
          down vote










          up vote
          0
          down vote









          I have two comments of the tweaking kind:



          1) any variable that is shared between threads has to be volatile. this is true even for static variables that have one value throughout the JVM (actually it is per class loader but this is irrelevant here). The reason for that is that threads can locally cache the value of variables. volatile variables force the thread to read the global value each time.



          You might also want to take a look at AtomicInteger which is an int that is guaranteed to be incremented synchronously and that has the same value for all running threads.



          2) while synchronized will work, Java concurrency package has several Lock mechanisms that allow for better control over the synchronization process. of relevancy here are ReentrantLock, ReadWriteLock.






          share|improve this answer













          I have two comments of the tweaking kind:



          1) any variable that is shared between threads has to be volatile. this is true even for static variables that have one value throughout the JVM (actually it is per class loader but this is irrelevant here). The reason for that is that threads can locally cache the value of variables. volatile variables force the thread to read the global value each time.



          You might also want to take a look at AtomicInteger which is an int that is guaranteed to be incremented synchronously and that has the same value for all running threads.



          2) while synchronized will work, Java concurrency package has several Lock mechanisms that allow for better control over the synchronization process. of relevancy here are ReentrantLock, ReadWriteLock.







          share|improve this answer













          share|improve this answer



          share|improve this answer











          answered Jan 8 at 8:45









          Sharon Ben Asher

          2,073512




          2,073512











          • So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
            – Arunabh
            Jan 8 at 9:27










          • I don't know about this specific scenario.
            – Sharon Ben Asher
            Jan 8 at 9:49
















          • So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
            – Arunabh
            Jan 8 at 9:27










          • I don't know about this specific scenario.
            – Sharon Ben Asher
            Jan 8 at 9:49















          So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
          – Arunabh
          Jan 8 at 9:27




          So if I make the static variable volatile and make the variable an AtomicInteger, is this program good enough to be written in an interview? Thanks for your answer.
          – Arunabh
          Jan 8 at 9:27












          I don't know about this specific scenario.
          – Sharon Ben Asher
          Jan 8 at 9:49




          I don't know about this specific scenario.
          – Sharon Ben Asher
          Jan 8 at 9:49












           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f184559%2falternate-threads-to-print-even-and-odd-numbers%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

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

          C++11 CLH Lock Implementation