[Last Call] Learn how to a build a cloud-first strategyRegister Now

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

how to synchronize?

How to synchronize the test method here? The output prints "count is not equlat to count1" . Why is it happening?

public class t1 extends Thread {
int count = 0;

int count1 = 0;

public void run() {
System.out.println("Thread t1 started ............");
while (true) {
test();
if (count != count1) {
System.out.println("count is not equlat to count1" + count
+ " " + count1);
}
}
}

public synchronized void test() {
this.count++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.count1++;
System.out.println(count + " " + count1);

}
------------------------------------------------------------------
public class threadMain extends Thread {
public static void main(String str[]) {
threadMain tt = new threadMain();
//Start this thread
tt.start();
}
threadMain() {
//Start t1 thread
tt1 = new t1();
tt1.start();
}

public void run() {
System.out.println("Thread Main started ............");
while (true) {
//This thread is calling test() method of t1
//t1 is thread by itself and it is also calling test()
tt1.test();
}
}
public t1 tt1;
}
0
potiyan
Asked:
potiyan
  • 2
1 Solution
 
objectsCommented:
looks like you also want to synchronize the if statement:


synchronized (this)
{
   if (count != count1) {
      System.out.println("count is not equlat to count1" + count+ " " + count1);
   }
}
0
 
Mayank SAssociate Director - Product EngineeringCommented:
I don't think that would help because count and count1 are not being modified anywhere else but the test () method. And control would reach the if () statement only after the test () method has executed.

It looks the code that has been posted will not even compile. Can you post the actual code you are using?
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Oh, already closed :)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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