[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 179
  • Last Modified:

Threads - check if runs correctly

Hello Experts,

I have four classes below [in the code snippet] one Updater, one Checker, one Data, and one ThreadTest which runs the two threads.

what i want is to create three different variations of checking that the code always runs correctly
1)one  which uses synchronized methods
 2)one which uses Java 5 locks
 3)one which uses semaphores

Can anyone tell me how can i do the above checks ?

Thanks in advance!
//ThreadTest
public class ThreadTest {
	
	public static void main( )
	   {
	      //declare the threads
	      ThreadTest Updater = new ThreadTest( );
	      ThreadTest Checker = new ThreadTest( );
 
	      Updater.start();
	      Checker.start(); 
 
	        
	      System.err.println( "Started two Threads, main ends\n" );
	      
	   }
 
	private void start() {
		
		
	}
}
 
//Data
public class Data { 
 Integer counter1 = 0; 
 Integer counter2 = 0; 
 Integer counter3 = 0; 
 
 Integer add() {   
     Integer temp1 = counter1; 
     Integer temp2 = counter2; 
     Integer temp3 = counter3; 
     return temp1 + temp2 + temp3; 
 } 
 
 void inc () { 
      counter1 = counter1 + 1; 
      counter2 = counter2 + 1; 
      counter3 = counter3 + 1; 
      return; 
 } 
}  
 
//Updater
public class Updater implements Runnable { 
 
      Data data = null; 
  
    Updater(Data data) { 
   
  this.data = data; 
    } 
  
    public void run () { 
    
          for(Integer i = 0; i < 50000; i++)  
           data.inc(); 
    
         System.out.println("Updater ended normally"); 
    
    } 
      } 
 
 
//Checker 
public class Checker implements Runnable { 
 
     Data data = null; 
  
     Checker(Data data) { 
   this.data = data; 
     } 
  
     public void run () { 
 
         for(Integer i = 0; i < 50000; i++) { 
 
           Integer r = data.add(); 
 
           if (!(r % 3 == 0)) { 
              // As inc() in Data increments all three counters, 
              // the result of read() should always be a multiple 
              // of 3, so this should never happen.... 
              System.out.println("Checker did NOT end normally!");       
              System.exit(-1); 
           } 
         }      
         System.out.println("Checker ended normally"); 
      } 
     }

Open in new window

0
perdoname_
Asked:
perdoname_
  • 2
1 Solution
 
Ajay-SinghCommented:
0
 
Ajay-SinghCommented:
was wondering what answer should quality for grade A? ready made code?
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now