Multithreading in Java : Part II

in utopian-io •  7 years ago  (edited)

What will I learn?

This tutorial covers following topics:

  • Creating threads by Converting classes
  • Differences between two ways of creating threads

Requirements

  • A laptop /PC with Mac OS/ Linux/ Windows
  • Preinstalled OpenJDK
  • Preinstalled jvm
  • Preinstalled Code editor

Difficulty

Intermediate, you must have good knowledge of basics of Java programming to catch up this tutorial.

Tutorials Content

In the previous tutorial, we learned different stages of Lifecycle of thread and creating threads using thread class. Now we will create the thread by converting classes into threads.

Converting class to thread

In our first part of this tutorial series we discussed in detail on how threads are created using thread class, now we are converting classes into a thread. This way of creating threads is also known as the creation of thread by implementing a Runnable interface.
Here, Runnable interface is implemented in class which declares the run() method which creates the thread. At first, we will create a class which implements the Runnable interface and then we run() method to create threads. And we will call start() method to run the thread.

Example:

We will see by example with two classes AreaSquare and PeriSquare to calculate area and perimeter of square respectively. Both of the classes implement Runnable interfaces.
We use run() method to create thread objects and is initiated in ThreadTesting class by start() method.

//creating class which implements Runnable interface
class AreaSquare implements Runnable
{    
    //run method to create thread
    public void run()
    {   
        int[] len = {5,6,7};
        for (int i = 0; i< len.length; i++ )
        {
         int area = len[i] * len[i];    
                 System.out.println("Area is " + area);
        }
        }
}    

class PeriSquare implements Runnable
{    
    public void run()
    {
        int[] len = {7,8,9};
        for (int i = 0; i< len.length; i++ )
        {
         int perimeter = 4 * len[i];    
                 System.out.println("Perimeter is " + perimeter); 
        }
    }
}

class ThreadTesting
{
    //main method
    public static void main(String args[])
    {
        //creating class object
        AreaSquare a = new AreaSquare();
        //thread object
        Thread thread1 = new Thread(a);
        //invoking run method
        thread1.start();
        
        PeriSquare b = new PeriSquare();
        Thread thread2 = new Thread(b);
        thread2.start();
       
    }
}   

Output:

Area is 25
Perimeter is 28
Area is 36
Perimeter is 32
Area is 49
Perimeter is 36
BUILD SUCCESSFUL (total time: 0 seconds)

As mentioned in first part of this tutorial, we have three threads in total, two threads we created by implementing the Runnable interface and one as the main program.
All the threads are running independently and they may be executed whenever processor can have time for them thus, they don't have a special sequence of outputs.

Differences between the two ways of creating threads

We created threads by extending Thread class and by implementing the Runnable interface. There are differences between these methods and advantages of using one way over another. Some of them are listed below:

  • Implementing runnable interface will not inherit all the method we needed or not needed of Thread class as extending Thread class.

  • As multiple inheritance is not supported in Java, extending a class with Thread class won't allow that particular class to extend other class but using Runnable interface we can extend our Thread class.

  • Just to use run() method we have to extend our class with Thread class which means we aren't modifying any other thing and it isn't good practice in object-oriented programming so implementing Runnable will be the best choice while creating threads.

  • Runnable interface shares same object space whereas extending Thread class has different object space for different threads, thus implementing Runnableuses less memory.

Conclusion

We learned to create threads by converting the class to a thread and concluded implementing the Runnable interface is better than extending Thread class while creating threads.

All above codes can be found on my GitHub link. Click here to download.

What's next?

In coming tutorials we will learn:

  • Communication between threads
  • Thread priority and more.

Curriculam

Multithreading in Java : Part I



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  7 years ago Reveal Comment

Congratulations @programminghub, this post is the ninth most rewarded post (based on pending payouts) in the last 12 hours written by a User account holder (accounts that hold between 0.1 and 1.0 Mega Vests). The total number of posts by User account holders during this period was 2613 and the total pending payments to posts in this category was $4543.31. To see the full list of highest paid posts across all accounts categories, click here.

If you do not wish to receive these messages in future, please reply stop to this comment.

Thanks

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thank you

This info is useful to the other users that who want to take programming. You can follow me on @thenerdkid
I'll be posted some codes also in my page soon.

Thanks

Hey @programminghub I am @utopian-io. I have just upvoted you!

Achievements

  • WOW WOW WOW People loved what you did here. GREAT JOB!
  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • You are generating more rewards than average for this category. Super!;)
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

  ·  7 years ago (edited)

Humm. Interesting. I look forward to your next tutorials.

Sure, don't forget to follow @programminghub to see my tutorials on your feed.