perdoname_
asked on
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!
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");
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
was wondering what answer should quality for grade A? ready made code?