I tested my skills compared to Thread
. When I implemented the interface Runnable
and synchronized
the run method, I got an absolute result. But, expanding the class Thread
, the result was unpredictable. The following are two cases. I think that threads in both cases use the same resource.
case 1 Runnable
class Counter{
int count;
public void doCount(){
count=count+1;
}
public int getCount(){
return count;
}
}
public class One implements Runnable{
Counter counter = new Counter();
public void run(){
synchronized (this) {
for(int i=0;i<10000;i++){
counter.doCount();
}
}
}
public static void main(String[] args) throws InterruptedException {
One one = new One();
Thread t1 = new Thread(one);
Thread t2 = new Thread(one);
t1.start();
t2.start();
Thread.sleep(2000);
System.out.println(one.counter.getCount());
}
}
case 2 Thread
class Counter{
int count;
public void doCount(){
count=count+1;
}
public int getCount(){
return count;
}
}
public class One extends Thread{
Counter counter;
One(Counter counter){
this.counter = counter;
}
public void run(){
synchronized (this) {
for(int i=0;i<10000;i++){
counter.doCount();
}
}
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
One o1 = new One(counter);
One o2 = new One(counter);
o1.start();
o2.start();
Thread.sleep(2000);
System.out.println(counter.getCount());
}
}
for case 1, I get 20,000 output every time. but for case 2, I get random values every time. Why is this so? case 2 also uses the same resource among two threads, then why they stop receiving synchronized
. can someone explain this .. I go nuts !!
source
share