1

I wrote a Multithreaded program in Java given below :-

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        Counter counter = new Counter();

        int val = counter.getValue();
        while(val < 5){
            val = counter.getValue();
            System.out.println("In main thread : "+val);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

}
}

class Counter implements Runnable {

    private int countValue;
    Counter(){
        countValue = 0;
        Thread thread = new Thread(this ,"Counter A");
        Thread thread1 = new Thread(this    ,"Counter B");
        thread.start();
        thread1.start();
    }

    int getValue(){
        return countValue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while( countValue < 5){

                System.out.println("In child thread : "+ ++countValue );
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    }

}
}

and output of program is output :-

In main thread : 0  
In child thread : 2   
In child thread : 1   
In child thread : 3  
In child thread : 3  
In child thread : 4  
In child thread : 5  
In main thread : 5  

Can anybody explain me in detail how this output came.Thank you in advance

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
pranay godha
  • 625
  • 2
  • 7
  • 13
  • What part of this, specifically, do you need help understanding? How does it differ from what you expected? – Oliver Charlesworth Jan 10 '12 at 00:03
  • and is this homework? or are you just exploring threads? – John Gardner Jan 10 '12 at 00:07
  • possible duplicate of [Unable to understand the working of Threads- Runnable Interface](http://stackoverflow.com/questions/5644311/unable-to-understand-the-working-of-threads-runnable-interface) (The OP's code is slightly different, the reason for the output is the same) – Brian Roach Jan 10 '12 at 00:07
  • like in output after printing "In main thread : 0 " how it is printing directly "In child thread : 2" . It should be "In child thread : 1" first. – pranay godha Jan 10 '12 at 00:08
  • 2
    why do you think it should work that way? you have 2 threads updating the value in contention, with no synchronization. If you had only *one* child thread, it might work like you expect. increasing the number of child threads is going to give you even more strange behavior. This is the reason things like synchronized and **entire frameworks** exist for parallel processing. – John Gardner Jan 10 '12 at 00:11
  • Try reading [Java Concurrency in Practice](http://jcip.net/) if you really want to explore threads in Java, it's well known and well liked. – Maarten Bodewes Jan 10 '12 at 02:06

1 Answers1

3

You have 3 threads (main and 2 child) that are all running in parallel (unless you have a single proc box) that are all reading and writing a resource countValue that isn't protected by any kind of synchronization.

When you do things like this, you'll get apparently random output.

John Gardner
  • 24,225
  • 5
  • 58
  • 76
  • so how can I protect countValue by which synchronization method? – pranay godha Jan 10 '12 at 00:26
  • simplest would probably be to look into `AtomicInteger` http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html but otherwise, you probably need to read up on how threading works, use of `synchronized`, etc. I'd also suggest not updating the value as a *side effect* of the println statement. – John Gardner Jan 10 '12 at 00:30
  • 2
    volatile has some wierd usage and side effects, hence the existance of the AtomicX types. For example: `...because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write (like x++) as an atomic operation...` – John Gardner Jan 10 '12 at 00:37