<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Akanksha Sharma</title>
    <description>The latest articles on DEV Community by Akanksha Sharma (@akanksha).</description>
    <link>https://dev.to/akanksha</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F908380%2F43cdad6d-6d78-49b0-8782-03a1bfe21e10.jpeg</url>
      <title>DEV Community: Akanksha Sharma</title>
      <link>https://dev.to/akanksha</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/akanksha"/>
    <language>en</language>
    <item>
      <title>Multi threading</title>
      <dc:creator>Akanksha Sharma</dc:creator>
      <pubDate>Sun, 04 Sep 2022 17:13:17 +0000</pubDate>
      <link>https://dev.to/akanksha/multi-threading-f21</link>
      <guid>https://dev.to/akanksha/multi-threading-f21</guid>
      <description>&lt;h2&gt;
  
  
  What are threads?
&lt;/h2&gt;

&lt;p&gt;a thread is a part of a &lt;a href="https://en.wikipedia.org/wiki/Process_(computing)"&gt;process&lt;/a&gt; under execution. When we run a java program, we often just run the process of &lt;a href="https://en.wikipedia.org/wiki/Java_virtual_machine"&gt;JVM&lt;/a&gt;. JVM triggers the the 'main' thread of the program under execution for us and creates a &lt;a href="https://en.wikipedia.org/wiki/Call_stack"&gt;call stack&lt;/a&gt; beginning with main().&lt;/p&gt;

&lt;p&gt;We can have multiple threads doing different things in, what appears to be the same time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why would I use multiple threads?
&lt;/h2&gt;

&lt;p&gt;using multiple threads enable us to perform multiple tasks within the same application. For example, &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;While using an application like a text editor, a thread caters to editing tasks, another can maintain cache, another can run spell check etc. &lt;/li&gt;
&lt;li&gt;On a server, we can have multiple threads catering to multiple clients&lt;/li&gt;
&lt;li&gt;While playing games, we can have dedicated threads for user control while other threads can implement game logic&lt;/li&gt;
&lt;li&gt;We can have multiple threads doing numerous asynchronous tasks for any application&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to Use Multiple Threads?
&lt;/h2&gt;

&lt;p&gt;There are two ways of implementing multi threading:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Implement Runnable Interface&lt;/li&gt;
&lt;li&gt;Extend Thread Class&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The Runnable Interface and the Thread class are provided in the, &lt;a href="https://docs.oracle.com/javase/7/docs/api/java/lang/package-summary.html"&gt;java.langs&lt;/a&gt; package, therefore, are implicitly accessible in all java programs.&lt;/p&gt;

&lt;p&gt;For understanding the implementation of multi threading. Lets take an example of teaching at a school. Bob is a teacher, he teaches. Sally is a worker, she works. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2VgBUQAP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/35s8wnpnpwc8w5n5qsa6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2VgBUQAP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/35s8wnpnpwc8w5n5qsa6.png" alt="Implementing Runnable vs extending Thread" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Bob is a specialized worker (a teacher), whereas Sally is a generalized worker who needs a job.&lt;/p&gt;

&lt;p&gt;In order to make a bob thread, we first need to define a teacher&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Teacher extends Thread
{
    @Override
    public void run()
    {
        System.out.println("teach teach 👨‍🏫");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the Thread class (with a capital T) defines a worker, a thread is an instance of the Thread class which is a worker. Instead of defining the teacher, we can also define the job of teaching&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Teach implements Runnable
{
    @Override
    public void run() {
        System.out.println("teach teach 👨‍🏫");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we implement the Runnable interface. In both cases, we must override the method run(). run() contains the set of instructions for getting the job done. &lt;/p&gt;

&lt;p&gt;And finally we can get Bob and Sally to work&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class School
{
    public static void main(String[] args) {
        Teacher bob=new Teacher();
        bob.start();
        Thread sally=new Thread(new Teach());
        sally.start();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we instantiate the teacher bob and the call the method start(), this creates a separate call stack that starts with run() defined in the class Teacher. Similarly, we instantiate the thread sally, and pass an instance of the job Teach in its constructor. On calling start(), another call stack beginning with the run() defined in class Teach is created. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;When we use the Runnable interface, we essentially define a job and then assign it to a thread. Whereas, when we extend the Thread class, we are defining a worker.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use either?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Apart from the conceptual difference, there's also a practical difference between the two. After extending class Thread, class Teacher cannot extend any other classes, whereas class Teach can still extend other classes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;So if you wish to extend other classes, you must implement the Runnable interface.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now we have 3 call stack, a main, one crated by bob, and one created by sally. All working at the apparent same time. &lt;/p&gt;

&lt;h2&gt;
  
  
  Apparent, huh?
&lt;/h2&gt;

&lt;p&gt;Even though we are using multiple threads, They are all part of the same process, the JVM. Even though your PC might have multiple processor, the JVM must run on only one of them. Therefore, all threads have access to that same processor. Even though it looks like the JVM allows multiple threads to execute concurrently, &lt;em&gt;in reality all threads take turns using the processor.&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;Allocation of computing resources is done by java's thread scheduler. It is some sort of a gate keeper who gets to decide which thread will get to use which resources, and for how long.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OfnlmYrz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gfqj8wfhs3i5zko1cr1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OfnlmYrz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gfqj8wfhs3i5zko1cr1.png" alt="Thread Scheduler" width="880" height="495"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The thread scheduler works at will, and there's no way for us to control or predict how it should schedule the threads. Although we can influence its decision, but we cannot know for certain when will it schedule a thread for execution. It may even &lt;a href="https://en.wikipedia.org/wiki/Preemption_(computing)"&gt;preempt&lt;/a&gt; certain threads from completing and let other threads execute first. Or it may &lt;a href="https://www.educative.io/answers/what-is-a-starvation-problem-in-an-operating-system"&gt;starve&lt;/a&gt; other threads.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do multiple threads run?
&lt;/h2&gt;

&lt;p&gt;Threads exist in 3 different states. Runnable (ready), Running, and Asleep. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6rKGcmw_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c8evlh0wtg6g3jjl74f8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6rKGcmw_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c8evlh0wtg6g3jjl74f8.png" alt="3 states of threads" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above example, &lt;code&gt;Teacher bob=new Teacher();&lt;/code&gt; and &lt;code&gt;Thread sally=new Thread(new Teach());&lt;/code&gt; creates 2 new thread objects. &lt;code&gt;bob.start();&lt;/code&gt; and &lt;code&gt;sally.start();&lt;/code&gt; bring them in ready state. Then its upto the Thread Scheduler to pick them and let them execute their jobs, or interrupt them and put them to sleep. Ultimately, they will finish their tasks as their call stacks fall out of existence.  &lt;/p&gt;

&lt;p&gt;We can time an interrupt using the sleep() method. It guarantees that for the specified period of time, the thread shall not execute. Let's redefine the teacher's job to teach 5 lectures in a day.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Teacher extends Thread {
    public void teach() {
        System.out.println(this.getName()+" teach");
    }

    @Override
    public void run() {
        for(int i=0; i&amp;lt;5; i++) {
            teach();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now lets instantiate bob and sally and run the program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class School
{
    public static void main(String[] args) {
        Teacher bob=new Teacher();
        bob.setName("Bob");
        Teacher sally=new Teacher();
        sally.setName("Sally");

        bob.start();
        sally.start();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here are the results from 3 runs I made: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NB6dHwDr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/okz10xowlah0vtn1ytvu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NB6dHwDr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/okz10xowlah0vtn1ytvu.png" alt="experiment 1" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;you can see preemption in the first 2 cases. However, in the third case, Sally was made to wait until Bob finishes.&lt;/p&gt;

&lt;p&gt;Lets make an explicit interrupt and make Sally and Bob take a 5 sec (or 5000 milliseconds) nap after every lecture.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Teacher extends Thread {
    public void teach() {
        System.out.println(this.getName()+" teach");
    }

    @Override
    public void run() {
        for(int i=0; i&amp;lt;5; i++) {
            teach();
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;sleep() throws InterruptedException, although its unlikely to be interrupted. However, the exception must be handled. &lt;/p&gt;

&lt;p&gt;results from the run: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8gbRYpI5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/72sxybm8qcdw3cbt8zlc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8gbRYpI5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/72sxybm8qcdw3cbt8zlc.png" alt="experiment 2" width="880" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;here Bob and Sally did go to sleep after every lecture. In Run 3, we can see Sally going to sleep, waking up and even teaching again even before Bob got the chance to teach. &lt;/p&gt;

&lt;h2&gt;
  
  
  Further Reading
&lt;/h2&gt;

&lt;p&gt;Now multi threading seems great. We can use it for anything and everything. Right? githR?&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vCb1OCTR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/RbelQBq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vCb1OCTR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.imgur.com/RbelQBq.png" alt="problem" width="505" height="256"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
    </item>
  </channel>
</rss>
