0
class SalesPersons implements Runnable{
      String[] names ={"Shubham","Shreyanshi","Sanjay","Sujeet","Utsab"};
      public void run(){
            for(int loop=0;loop<names.length();loop++){
                syso(names[loop]);
            }
      }
 }
class Days implements Runnable{
      String[] days ={"Sat","Sun","Mon","Tue","Wed","Thu","Fri"};
      public void run(){
            SalesPersons sp_obj = new SalesPersons();
            Thread t2 = new Thread(sp_obj,"sales_persons");
            t2.start();
            for(int loop=0;loop<days.length();loop++){
               if(days[loop].equalsIgnoreCase("Sun"))
                  t2.suspend();
               if(days[loop].equalsIgnoreCase("Wed"))
                  t2.resume();
               syso(days[loop]);
            }
      }
      public static void main(String args[]){
          Days day_obj = new  Days();
          Thread t1 = new Thread(day_obj,"days");
          t1.start();
      }
 }

 Desired output: 
               Sat           <--|---Thread randomness but as per syso order
               Shubham       <--|   
               Sun           <--| 
               Mon              |---Fixed order
               Tue           <--|
               Wed           <--|
               Shreyanshi       |
               Sanjay           |
               Thu              |---Thread randomness but as per syso order 
               Fri              |
               Sujeet           |
               Utsab         <--|  

 Sometimes I am getting:

 Sample:1
 Sat
 Sun

 Sample:2
 Sat
 Shubham

 Sample:3
 Sat
 Shubham
 Sun

 Sample:4
 Sat

 Sample:5
 Sat
 Sun
 Mon
 Tue
 Wed

Why is that? There should be 12 lines printed considering the randomness of printing because of threads competing with each other. But sun mon tue should be printed in exact order each time. I can't understand why I am getting undesired outputs as such given in sample output above.

Shivind
  • 67
  • 7
  • I think wait() and notify() methods will help, in multithreaded env, there is no thread synchronization by default, so programmer should handle it. – dkb Dec 10 '17 at 19:34
  • @dkb Do I have to read about thread synchronization to understand why I am getting this undesired output ? – Shivind Dec 10 '17 at 19:52
  • Yes, but for summary, this will suffice: https://stackoverflow.com/questions/25051031/why-thread-execution-is-giving-different-output and https://stackoverflow.com/questions/7915337/what-makes-the-execution-order-of-threads-unpredictable – dkb Dec 10 '17 at 20:10

0 Answers0