Multi-Threading in Java: Tutorial 7


08 Oct  

One thing that I really love in java is the fact that it supports multi-threading. This means that you can do many tasks in parallel. Well, I would like to clarify one point here. If you have got only one processor in your system, then you can perform only one task at a time. But this doesn’t mean that you can’t do multi-threading in Java. Actually your processor  performs operations very quickly so that when it switches between tasks we ,humans, can’t recognise it (akin to the logic behind your  TV screen or incandescent bulb).

Let’s come back to our topic. You can start a new thread just by invoking start() and you can run your new thread using run(). Since java.lang package is automatically called you don’t have to import anything explicitly.

 

You can comprehend it better once you see the code:

 

   1: class SampleA extends Thread

   2: {

   3:  public void run()

   4:  {

   5:      for (int a=1;a<3;a++)

   6:          System.out.println("This is from SampleA:" +a );

   7:  }

   8:  

   9: }

  10:  

  11: class SampleB extends Thread {

  12:         public void run()

  13: {

  14:     for (int b=1;b<3;b++)

  15:         System.out.println("This is from SampleB: "+b);

  16: }

  17: }

  18: class SampleC extends Thread {

  19:         public void run()

  20: {

  21:     for (int c=1;c<3;c++)

  22:         System.out.println("This is from Sample C: "+c);

  23: }

  24: }

  25: class  Threading {

  26:     public static void main(String args[])

  27:     {

  28:        new SampleA().start();

  29:        new SampleB().start();

  30:        new SampleC().start();

  31:     }

  32: }

 

Here you can see that our main starts the threads and run them.

So, if you execute the code you may get:

 

run:
This is from SampleA:1
This is from SampleA:2
This is from SampleB: 1
This is from SampleB: 2
This is from Sample C: 1
This is from Sample C: 2
 

You might ask where is the multi threading feature. If you want to see that, you will have to run it again:

 

run:
This is from SampleB: 1
This is from SampleB: 2
This is from SampleA:1
This is from SampleA:2
This is from Sample C: 1
This is from Sample C: 2

 

I guess this answers that question!

Here we are actually extending Thread which is in the lang package.

And we use new SampleA().start() for declaring and initiating our new thread.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Tags:


TechBlog on Facebook

Comments (1)

 

  1. stevep says:

    Hey guys. I’ve been a long time reader, but first time poster.

    Just want to say hi to others

Leave a Reply