Jump to content

multi threads in java

- - - - -

  • Please log in to reply
1 reply to this topic

#1
eman ahmed

eman ahmed

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
I know that multithreads in java allows me do multi tasks in the same time, but in the following code I'm not make a sense that the three threads done in the same time

public class myThreads

{


 

 public static void main(String [] args)

 {

   System.out.println("Begin main Function");

   mThread Thread_One = new mThread ("One",0,3);

   mThread Thread_Two = new mThread ("Two",4,7);

   mThread Thread_Three = new mThread("Three",8,11);

   

   Thread_One.start();

   Thread_Two.start();

   Thread_Three.start();

   

   System.out.println("End main Function");

   

 }// main

}//myThreads



class mThread extends Thread

{

 private String ThreadName;

 private int StartFrom;

 private int FinishTo;

 

 public mThread(String name, int n1, int n2)

 {

   ThreadName = name;

   StartFrom = n1;

   FinishTo = n2;

 }


 public void run(){

   for (int i=StartFrom; i<=FinishTo; i++)

     System.out.println(ThreadName+ "Counter:" +i);

 }



}//mThread

the output of the program are

Begin main Function
End main Function
OneCounter:0
OneCounter:1
OneCounter:2
OneCounter:3
TwoCounter:4
TwoCounter:5
TwoCounter:6
TwoCounter:7
ThreeCounter:8
ThreeCounter:9
ThreeCounter:10
ThreeCounter:11

why the statement " End main Function " printed before excute the threads ?
and if the 3 threads done simultanously
why the output beomes
OneCounter:0
TwoCounter:4
ThreeCounter:8
OneCounter:1
TwoCounter:5
ThreeCounter:9
and so on.........

#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
Because you can't make any assumption as in what order the threads will be executed. The output could be different every time!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users