<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Threading - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Threading - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 27 Jul 2026 22:42:51 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/threading/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Concurrency, parallelism, and the many threads of Santa Claus ? ]]>
                </title>
                <description>
                    <![CDATA[ Consider the following: Santa brings toys to all the good girls and boys. There are 7,713,468,100 people in the world in 2019, around 26.3% of which are under 15 years old. This works out to 2,028,642,110 children (persons under 15 years of age) in t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/concurrency-parallelism-and-the-many-threads-of-santa-claus/</link>
                <guid isPermaLink="false">66bd8f1effb0fc5947cc911e</guid>
                
                    <category>
                        <![CDATA[ Christmas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Computer Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ multithreading ]]>
                    </category>
                
                    <category>
                        <![CDATA[ parallelism ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Threading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Victoria Drake ]]>
                </dc:creator>
                <pubDate>Tue, 24 Dec 2019 01:18:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/cover-3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Consider the following: Santa brings toys to all the good girls and boys.</p>
<p>There are <a target="_blank" href="https://en.wikipedia.org/wiki/Demographics_of_the_world#Current_population_distribution">7,713,468,100 people</a> in the world in 2019, <a target="_blank" href="https://en.wikipedia.org/wiki/Demographics_of_the_world#Age_structure">around 26.3%</a> of which are under 15 years old. This works out to 2,028,642,110 children (persons under 15 years of age) in the world this year.</p>
<p>Santa doesn’t seem to visit children of every religion, so we’ll  generalize and only include Christians and non-religious folks.  Collectively that makes up <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_religious_populations#Adherent_estimates_in_2019">approximately 44.72%</a> of the population. If we assume that all kids take after their parents, then 907,208,751.6 children would appear to be Santa-eligible.</p>
<p>What percentage of those children are good? It’s impossible to know; however, we can work on a few assumptions. One is that Santa Claus functions more on optimism than economics and would likely have prepared  for the possibility that every child is a good child in any given year. Thus, he would be prepared to give a toy to every child. Let’s assume it’s been a great year and that all 907,208,751.6 children are getting toys.</p>
<p>That’s a lot of presents, and, as we know, they’re all made by Santa’s elves at his North China Pole workshop. Given that there are 365 days in a year and one of them  is Christmas, let’s assume that Santa’s elves collectively have 364 days to create and gift wrap 907,208,752 (rounded up) presents. That works out to 2,492,331.74 presents per day.</p>
<p>Almost two-and-a-half million presents per day is a heavy workload for any workshop. Let’s look at two paradigms that Santa might employ to hit this goal: concurrency, and parallelism.</p>
<h2 id="heading-a-sequential-process">A sequential process</h2>
<p>Suppose that Santa’s workshop is staffed by exactly one, very hard working, very tired elf. The production of one present involves four  steps:</p>
<ol>
<li>Cutting wood</li>
<li>Assembly and gluing</li>
<li>Painting</li>
<li>Gift-wrapping</li>
</ol>
<p>With a single elf, only one step for one present can be happening at any instance in time. If the elf were to produce one present at a time from beginning to end, that process would be executed <em>sequentially</em>. It’s not the most efficient method for producing two-and-a-half million presents per day; for instance, the elf would have to wait around doing nothing while the glue on the present was drying before moving on to the next step.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/sequence.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-concurrency">Concurrency</h2>
<p>In order to be more efficient, the elf works on all presents <em>concurrently</em>.</p>
<p>Instead of completing one present at a time, the elf first cuts all the wood for all the toys, one by one. When everything is cut, the elf assembles and glues the toys together, one after the other. This <a target="_blank" href="https://en.wikipedia.org/wiki/Concurrent_computing">concurrent processing</a> means that the glue from the first toy has time to dry (without needing more attention from the elf) while the remaining toys are glued together. The same goes for painting, one toy at a time, and finally wrapping.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/concurrency.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since one elf can only do one task at a time, a single elf is using the day as efficiently as possible by concurrently producing presents.</p>
<h2 id="heading-parallelism">Parallelism</h2>
<p>Hopefully, Santa’s workshop has more than just one elf. With more elves, more toys can be built simultaneously over the course of a day. This simultaneous work means that the presents are being produced in <em>parallel</em>. <a target="_blank" href="https://en.wikipedia.org/wiki/Parallel_computing">Parallel processing</a> carried out by multiple elves means more work happens at the same time.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/parallel.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Elves working in parallel can also employ concurrency. One elf can still tackle only one task at a time, so it’s most efficient to have multiple elves concurrently producing presents.</p>
<p>Of course, if Santa’s workshop has, say, two-and-a-half million  elves, each elf would only need to finish a maximum of one present per day. In this case, working sequentially doesn’t detract from the workshop’s efficiency. There would still be 7,668.26 elves left over to fetch coffee and lunch.</p>
<h2 id="heading-santa-claus-and-threading">Santa Claus, and threading</h2>
<p>After all the elves’ hard work is done, it’s up to Santa Claus to deliver the presents – all 907,208,752 of them.</p>
<p>Santa doesn’t need to make a visit to every kid; just to the one household tree. So how many trees does Santa need to visit? Again with broad generalization, we’ll say that the average number of children per household worldwide is <a target="_blank" href="https://en.wikipedia.org/wiki/Demographics_of_the_world#Total_fertility_rate">2.45, based on the year’s predicted fertility rates</a>. That makes 370,289,286.4 houses to visit. Let’s round that up to 370,289,287.</p>
<p>How long does Santa have? The lore says one night, which means one earthly rotation, and thus 24 hours. <a target="_blank" href="https://www.noradsanta.org/">NORAD confirms</a>.</p>
<p>This means Santa must visit 370,289,287 households in 24 hours (86,400 seconds), at a rate of 4,285.75 households per second, never mind the time it takes to put presents under the tree and grab a cookie.</p>
<p>Clearly, Santa doesn’t exist in our dimension. This is especially likely given that, despite being chubby and plump, he fits down a chimney (with a lit fire, while remaining unhurt) carrying a sack of toys containing presents for all the household’s children. We haven’t even considered the fact that his sleigh carries enough toys for every believing boy and girl around the world, and flies.</p>
<p>Does Santa exist outside our rules of physics? How could one entity manage to travel around the world, delivering packages, in under 24 hours at a rate of 4,285.75 households per second, and still have time for milk and cookies and kissing mommy?</p>
<p>One thing is certain: Santa uses the Internet. No other technology has yet enabled packages to travel quite so far and quite so quickly. Even so, attempting to reach upwards of four thousand households per second is no small task, even with the best gigabit internet hookup the North Pole has to offer. How might Santa increase his efficiency?</p>
<p>There’s clearly only one logical conclusion to this mystery: Santa Claus is a multithreaded process.</p>
<h2 id="heading-a-single-thread">A single thread</h2>
<p>Let’s work outward. Think of a <a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)">thread</a> as one particular task, or the most granular sequence of instructions that Santa might execute. One thread might execute the task, <code>put present under tree</code>. A thread is a component of a process, in this case, Santa’s process of delivering presents.</p>
<p>If Santa Claus is <a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)#Single_threading">single-threaded</a>, he, as a process, would only be able to accomplish one task at a time. Since he’s old and a bit forgetful, he probably has a set of instructions for delivering presents, as well as a schedule to abide by. These two things guide Santa’s thread until his process is complete.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/single.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Single-threaded Santa Claus might work something like this:</p>
<ol>
<li>Land sleigh at Timmy’s house</li>
<li>Get Timmy’s present from sleigh</li>
<li>Enter house via chimney</li>
<li>Locate Christmas tree</li>
<li>Place Timmy’s present under Christmas tree</li>
<li>Exit house via chimney</li>
<li>Take off in sleigh</li>
</ol>
<p>Rinse and repeat… another 370,289,286 times.</p>
<h2 id="heading-multithreading">Multithreading</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Thread_(computing)#Multithreading">Multithreaded</a> Santa Claus, by contrast, is the <a target="_blank" href="https://dc.fandom.com/wiki/Jonathan_Osterman_(Watchmen)">Doctor Manhattan</a> of the North Pole. There’s still only one Santa Claus in the world; however, he has the amazing ability to multiply his consciousness and accomplish multiple instruction sets of tasks simultaneously. These additional task workers, or worker threads, are created and controlled by the main process of Santa delivering presents.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/cover-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Each worker thread acts independently to complete its instructions. Since they all belong to Santa’s consciousness, they share Santa’s memory and know everything that Santa knows, including what planet they’re running around on, and where to get the presents from.</p>
<p>With this shared knowledge, each thread is able to execute its set of  instructions in parallel with the other threads. This multithreaded  parallelism makes the one and only Santa Claus as efficient as possible.</p>
<p>If an average present delivery run takes an hour, Santa need only spawn 4,286 worker threads. With each making one delivery trip per hour,  Santa will have completed all 370,289,287 trips by the end of the night.</p>
<p>Of course, in theory, Santa could even spawn 370,289,287 worker threads, each flying to one household to deliver presents for all the  children in it! That would make Santa’s process extremely efficient, and also explain how he manages to consume all those milk-dunked cookies without getting full. ????</p>
<h2 id="heading-an-efficient-and-merry-multithreaded-christmas">An efficient and merry multithreaded Christmas</h2>
<p>Thanks to modern computing, we now finally understand how Santa Claus manages the seemingly-impossible task of delivering toys to good girls and boys the world-over. From my family to yours, I hope you have a wonderful Christmas. Don’t forget to hang up your stockings on the router shelf.</p>
<p>Of course, none of this explains how reindeer manage to fly.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Multithreading in Java: How to Get Started with Threads ]]>
                </title>
                <description>
                    <![CDATA[ By Aditya Sridhar What is a Thread? A thread is a lightweight process. Any process can have multiple threads running in it. For example in a web browser, we can have one thread which will load the user interface and another thread which will actually... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-started-with-multithreading-in-java/</link>
                <guid isPermaLink="false">66d45d65b3016bf139028d19</guid>
                
                    <category>
                        <![CDATA[ Backend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ concurrency ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Threading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 13 Dec 2019 13:45:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/how-to-get-started-with-multithreading-in-java.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Aditya Sridhar</p>
<h1 id="heading-what-is-a-thread">What is a Thread?</h1>
<p>A thread is a lightweight process. Any process can have multiple threads running in it.</p>
<p>For example in a web browser, we can have one thread which will load the user interface and another thread which will actually retrieve all the data that needs to be displayed in that interface.</p>
<h1 id="heading-what-is-multithreading">What is MultiThreading?</h1>
<p>Multithreading enables us to run multiple threads concurrently.</p>
<p>For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed.</p>
<p>So multithreading improves the responsiveness of a system.</p>
<h1 id="heading-what-is-concurrency">What is Concurrency?</h1>
<p>Concurrency in the context of threads enables us to run multiple threads at the same time.</p>
<p>But do the threads really run at the same time?</p>
<h2 id="heading-single-core-systems">Single Core Systems</h2>
<p>The <strong>Thread Scheduler</strong> provided by the JVM decides which thread runs at any given time. The scheduler gives a small time slice to each thread.</p>
<p>So at any given time we have only one thread which is actually running in the processor. But because of the time slicing we get the feeling that multiple threads are running at the same time.</p>
<h2 id="heading-multi-core-systems">Multi Core Systems</h2>
<p>Even in multiple core systems the thread scheduler is involved. But since we have multiple cores, we can actually have multiple threads running at the exact same time.</p>
<p>For example if we have a dual core system, then we can have 2 threads running at the exact same time. The first thread will run in the first core, and the second thread will run in the second core.</p>
<h1 id="heading-why-is-multithreading-needed">Why is Multithreading needed?</h1>
<p>Multithreading enables us to improve the responsiveness of a system.</p>
<p>For example in a web browser, if everything ran in a single thread, then system would be completely unresponsive whenever data was being fetched to display. For example, if it takes 10 seconds to fetch the data, then in that 10 seconds we wont be able to do anything else in the web browser like opening new tabs, or even closing the web browser.</p>
<p>So running different parts of a program in different threads concurrently helps improve the responsiveness of a system.</p>
<h1 id="heading-how-to-write-multithreaded-programs-in-java">How to write Multithreaded Programs in Java</h1>
<p>We can create threads in Java using the following</p>
<ul>
<li>Extending the thread class</li>
<li>Implementing the runnable interface</li>
<li>Implementing the callable interface</li>
<li>By using the executor framework along with runnable and callable tasks</li>
</ul>
<p>We will look at callables and the executor framework in a separate blog. In this article I will be mainly focussing on extending the thread class and implementing the runnable interface.</p>
<h2 id="heading-extending-the-thread-class">Extending the Thread Class</h2>
<p>In order to create a piece of code which can be run in a thread, we create a class and then extend the <strong>thread</strong> class. The task being done by this piece of code needs to be put in the <strong>run()</strong> function. </p>
<p>In the below code you can see that <strong>worker</strong> is a class which extends the <strong>thread</strong> class, and the task of printing numbers 0 to 5 is being done inside the <strong>run()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}
</code></pre>
<p>In the above code <strong>Thread.currentThread().getName()</strong> is used to get the name of the current thread which is running the code.</p>
<p>In order to create a <strong>thread</strong>, we just need to create an instance of the worker class. And then we can start the thread using the <strong>start()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadClassDemo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Thread t1 = <span class="hljs-keyword">new</span> Worker();
        Thread t2 = <span class="hljs-keyword">new</span> Worker();
        Thread t3 = <span class="hljs-keyword">new</span> Worker();
        t1.start();
        t2.start();
        t3.start();

    }
}
</code></pre>
<p>In the above code, we are creating 3 threads (t1,t2 and t3) from the worker class. Then we are starting the threads using the <strong>start()</strong> function.</p>
<p>Here is the final code for creating a thread by extending a thread class:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">5</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadClassDemo</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Thread t1 = <span class="hljs-keyword">new</span> Worker();
        Thread t2 = <span class="hljs-keyword">new</span> Worker();
        Thread t3 = <span class="hljs-keyword">new</span> Worker();
        t1.start();
        t2.start();
        t3.start();

    }
}
</code></pre>
<p>Here is the output we get by running the above code:</p>
<p><img src="https://adityasridhar.com/assets/img/posts/how-to-get-started-with-multithreading-in-java/thread-class-output.png" alt="Thread Class output" width="525" height="295" loading="lazy"></p>
<p>You can see that all the 3 threads have printed the numbers from 0 to 5.</p>
<p><strong>You can also clearly see from the output that the 3 threads do not run in any particular sequence</strong></p>
<h2 id="heading-implementing-the-runnable-interface">Implementing the Runnable Interface</h2>
<p>In order to create a piece of code which can be run in a thread, we create a class and then implement the <strong>runnable</strong> interface. The task being done by this piece of code needs to be put in the <strong>run()</strong> function. </p>
<p>In the below code you can see that <strong>RunnableWorker</strong> is a class which implements <strong>runnable</strong> interface, and the task of printing numbers 0 to 4 is being done inside the <strong>run()</strong> function.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableWorker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}
</code></pre>
<p>In order to create a thread, first we need to create an Instance of <strong>RunnableWorker</strong> which implements the <strong>runnable</strong> interface.</p>
<p>Then we can create a new thread by creating an instance of the <strong>thread</strong> class and passing the instance of <strong>RunnableWorker</strong> as the argument. This is shown in the code below:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Runnable r = <span class="hljs-keyword">new</span> RunnableWorker();
        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();

    }

}
</code></pre>
<p>The above code creates a runnable instance r. Then it create 3 threads (t1, t2 and t3) and passes <strong>r</strong> as the argument to the 3 threads. Then the <strong>start()</strong> function is used to start all 3 threads.</p>
<p>Here is the complete code for creating a thread by implementing the runnable interface:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableWorker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    }

}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Runnable r = <span class="hljs-keyword">new</span> RunnableWorker();
        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();

    }

}
</code></pre>
<p>On running the above code, we will get the following output. The sequence of the output will change every time the code is run.</p>
<p><img src="https://adityasridhar.com/assets/img/posts/how-to-get-started-with-multithreading-in-java/runnable-interface-output.png" alt="Runnable Interface output" width="431" height="242" loading="lazy"></p>
<p><strong>Implementing the runnable interface is a better option than extending the thread class since we can extend only one class, but we can implement multiple interfaces in Java.</strong></p>
<h2 id="heading-runnable-interface-in-java-8">Runnable Interface in Java 8</h2>
<p>In Java 8, the runnable interface becomes a <strong>FunctionalInterface</strong> since it has only one function, <strong>run()</strong>.</p>
<p>The below code shows how we can create a runnable instance in Java 8.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RunnableFunctionalInterfaceDemo</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        Runnable r = () -&gt; {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
                System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
            }
        };

        Thread t1 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t2 = <span class="hljs-keyword">new</span> Thread(r);
        Thread t3 = <span class="hljs-keyword">new</span> Thread(r);

        t1.start();
        t2.start();
        t3.start();
    }

}
</code></pre>
<p>Here, instead of creating a class and then implementing the runnable interface, we can directly use a lambda expression to create a runnable instance as shown below:</p>
<pre><code class="lang-java">Runnable r = () -&gt; {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt;= <span class="hljs-number">4</span>; i++) {
            System.out.println(Thread.currentThread().getName() + <span class="hljs-string">": "</span> + i);
        }
    };
</code></pre>
<h1 id="heading-code">Code</h1>
<p>The code in this article is available in the following GitHub repo: <a target="_blank" href="https://github.com/aditya-sridhar/basic-threads-demo">https://github.com/aditya-sridhar/basic-threads-demo</a></p>
<h1 id="heading-congrats">Congrats ?</h1>
<p>You now know how to create threads by extending the thread class and by implementing the runnable interface.</p>
<p>I will discuss the thread life cycle and challenges while using threads in my next blog post.</p>
<p><strong>My Website</strong>: <a target="_blank" href="https://adityasridhar.com/">https://adityasridhar.com/</a></p>
<h3 id="heading-feel-free-to-connect-with-me-on-linkedinhttpswwwlinkedincominaditya1811-or-follow-me-on-twitterhttpswwwtwittercomadityasridhar18">Feel free to connect with me on <a target="_blank" href="https://www.linkedin.com/in/aditya1811">LinkedIn</a> or follow me on <a target="_blank" href="https://www.twitter.com/adityasridhar18">Twitter</a></h3>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Multiprocessing vs Multithreading in Python: What you need to know. ]]>
                </title>
                <description>
                    <![CDATA[ By Timber.io What Is Threading? Why Might You Want It? Python is a linear language. However, the threading module comes in handy when you want a little more processing power. Threading in Python cannot be used for parallel CPU computation. But it is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/multiprocessing-vs-multithreading-in-python-what-you-need-to-know-ef6bdc13d018/</link>
                <guid isPermaLink="false">66c35b9bc7095d76345eaff1</guid>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Threading ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 20 Jun 2018 16:57:16 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*lQy3P5ykmIM4G4Oa" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Timber.io</p>
<h4 id="heading-what-is-threading-why-might-you-want-it">What Is Threading? Why Might You Want It?</h4>
<p>Python is a linear language. However, the threading module comes in handy when you want a little more processing power.</p>
<p>Threading in Python cannot be used for parallel CPU computation. But it is perfect for I/O operations such as web scraping, because the processor is sitting idle waiting for data.</p>
<p>Threading is game-changing, because many scripts related to network/data I/O spend the majority of their time waiting for data from a remote source.</p>
<p>Because downloads might not be linked (for example, if you are scraping separate websites), the processor can download from different data sources in parallel and combine the result at the end.</p>
<p>For CPU intensive processes, there is little benefit to using the threading module.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ovUCmUeZrbYCgom4gc3TcPP9EZtq4INvmwTa" alt="Image" width="800" height="363" loading="lazy"></p>
<p>Threading is included in the standard library:</p>
<pre><code><span class="hljs-keyword">import</span> threading <span class="hljs-keyword">from</span> queueimport Queueimport time
</code></pre><p>You can use <code>target</code> as the callable object, <code>args</code> to pass parameters to the function, and <code>start</code> to start the thread.</p>
<pre><code>def testThread(num):    print numif __name__ == <span class="hljs-string">'__main__'</span>:    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):        t = threading.Thread(target=testThread, arg=(i,))        t.start()
</code></pre><p>If you’ve never seen <code>if __name__ == '__main__':</code> before, it's basically a way to make sure the code that's nested inside it will only run if the script is run directly (not imported).</p>
<h4 id="heading-the-lock">The Lock</h4>
<p>You’ll often want your threads to be able to use or modify variables common between threads. To do this, you’ll have to use something known as a <code>lock</code>.</p>
<p>Whenever a function wants to modify a variable, it locks that variable. When another function wants to use a variable, it must wait until that variable is unlocked.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/7tzH0eWzoj2WDCWtQ4ofrUxBXhFBjcQ2eZVW" alt="Image" width="800" height="1152" loading="lazy"></p>
<p>Imagine two functions which both iterate a variable by 1. The lock allows you to ensure that one function can access the variable, perform calculations, and write back to that variable before another function can access the same variable.</p>
<p>You can use a print lock to ensure that only one thread can print at a time. This prevents the text from getting jumbled up (and causing data corruption) when you print.</p>
<p>In the code below, we’ve got ten jobs that we want to get done and five workers that will work on the job:</p>
<pre><code>print_lock = threading.Lock()def threadTest():    # when <span class="hljs-built_in">this</span> exits, the print_lock is released    <span class="hljs-keyword">with</span> print_lock:        print(worker)def threader():  <span class="hljs-keyword">while</span> True:    # get the job <span class="hljs-keyword">from</span> the front <span class="hljs-keyword">of</span> the queue    threadTest(q.get())    q.task_done()q = Queue()<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):    thread = threading.Thread(target = threader)    # <span class="hljs-built_in">this</span> ensures the thread will die when the main thread dies    # can set t.daemon to False <span class="hljs-keyword">if</span> you want it to keep running    t.daemon = True    t.start()<span class="hljs-keyword">for</span> job <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):    q.put(job)
</code></pre><h4 id="heading-multithreading-is-not-always-the-perfect-solution">Multithreading is not always the perfect solution</h4>
<p>I find that many guides tend to skip the negatives of using the tool they’ve just been trying to teach you. It’s important to understand that there are both pros and cons associated with using all these tools. For example:</p>
<ol>
<li>There is overhead associated with managing threads, so you don’t want to use it for basic tasks (like the example)</li>
<li>Threading increases the complexity of the program, which can make debugging more difficult</li>
</ol>
<h3 id="heading-what-is-multiprocessing-how-is-it-different-from-threading">What is Multiprocessing? How is it different from threading?</h3>
<p>Without multiprocessing, Python programs have trouble maxing out your system’s specs because of the <code>GIL</code> (Global Interpreter Lock). Python wasn't designed considering that personal computers might have more than one core (which shows you how old the language is).</p>
<p>The GIL is necessary because Python is not thread-safe, and there is a globally enforced lock when accessing a Python object. Though not perfect, it's a pretty effective mechanism for memory management. <em>What can we do?</em></p>
<p>Multiprocessing allows you to create programs that can run concurrently (bypassing the GIL) and use the entirety of your CPU core. Though it is fundamentally different from the threading library, the syntax is quite similar. The multiprocessing library gives each process its own Python interpreter, and each their own GIL.</p>
<p>Because of this, the usual problems associated with threading (such as data corruption and deadlocks) are no longer an issue. Since the processes don’t share memory, they can’t modify the same memory concurrently.</p>
<h4 id="heading-lets-get-started">Let’s get started</h4>
<pre><code><span class="hljs-keyword">import</span> multiprocessingdef spawn():  print(<span class="hljs-string">'test!'</span>)<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:  <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):    p = multiprocessing.Process(target=spawn)    p.start()
</code></pre><p>If you have a shared database, you want to make sure that you’re waiting for relevant processes to finish before starting new ones.</p>
<pre><code><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>):  p = multiprocessing.Process(target=spawn)  p.start()  p.join() # <span class="hljs-built_in">this</span> line allows you to wait <span class="hljs-keyword">for</span> processes
</code></pre><p>If you want to pass arguments to your process, you can do that with <code>args</code>:</p>
<pre><code><span class="hljs-keyword">import</span> multiprocessingdef spawn(num):  print(num)<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:  <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">25</span>):    ## right here    p = multiprocessing.Process(target=spawn, args=(i,))    p.start()
</code></pre><p>Here’s a neat example, because the numbers don’t come in the order you’d expect (without the <code>p.join()</code>).</p>
<h4 id="heading-drawbacks">Drawbacks</h4>
<p>As with threading, there are still drawbacks with multiprocessing … you’ve got to pick your poison:</p>
<ol>
<li>There is I/O overhead from data being shuffled around between processes</li>
<li>The entire memory is copied into each subprocess, which can be a lot of overhead for more significant programs</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>When should you use multithreading vs multiprocessing?</p>
<ul>
<li>If your code has a lot of I/O or Network usage, multithreading is your best bet because of its low overhead.</li>
<li>If you have a GUI, use multithreading so your UI thread doesn’t get locked up.</li>
<li>If your code is CPU bound, you should use multiprocessing (if your machine has multiple cores)</li>
</ul>
<p><em>Just a disclaimer: we’re a logging company here @ Timber. We’d love it if you tried out <a target="_blank" href="https://timber.io/">our product</a> (it’s seriously great!), but that’s all we’re going to advertise it.</em></p>
<p>If you’re interested in getting more posts from Timber in your inbox, feel free to sign up <a target="_blank" href="http://eepurl.com/dxWQxr">here</a>. We promise there’ll be no spam, just great content on a weekly basis.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/TfypoIZnTArPPIDyCyeOzyDi8ybZKDcqnaq6" alt="Image" width="958" height="724" loading="lazy"></p>
<p><em>Originally published at <a target="_blank" href="https://timber.io/blog/multiprocessing-vs-multithreading-in-python-what-you-need-to-know/">timber.io</a>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
