Click here to Skip to main content
15,887,326 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a code for thread execution in Java.. But the threads are not working concurrently.. Here is the code..

Java
class Abc {

    public static void main(String[] ar){
        Mythread mt = new Mythread();
            mt.start();
            Mythread mt1 = new Mythread();
            mt1.start();
    }
}
class Mythread extends Thread{
    public void run(){
        for(int i = 0; i<= 9; i++){
            System.out.println(Thread.currentThread().getId() + " " + i);
        }
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException iex){

        }
    }
}

I expect the output to be:
id1 0
id2 0
id1 1
id2 1
id1 2
id2 2
id1 3
id2 3
id1 4
id2 4
id1 5
id2 5
id1 6
id2 6
id1 7
id2 7
id1 8
id2 8
id1 9
id2 9

But I am getting random sequence of output..Please point out what I am doing wrong!

What I have tried:

Implementing concurrent Javathreads
Posted
Updated 12-Feb-18 23:41pm
Comments
Ziee-M 12-Feb-18 11:27am    
Well thats exactly how threads are supposed to function, if you had an output like the one you posted, then there would be a problem.
There are so many GREAT articles about threading on CodeProject, just search and read few of them.
CPallini 12-Feb-18 11:56am    
My (virtual) 5.
Ziee-M 12-Feb-18 13:17pm    
Thanks CPalliani :)

1 solution

Hey there,
The thing with threads in java is that the thread scheduler can do whatever it feels like doing unless you use specific functions like the join(), wait() etc even the yield() method isn't guaranteed to run each time you call it because it's more of a type a request which which is why you cannot depend on it.
So, the output which you were expecting is one of the possible outputs but by no means it's the only thing which you'll get. But this doesn't mean that your threads aren't running concurrently.
Hope this helps.
Cheers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900