{"id":8043,"date":"2014-06-17T09:00:02","date_gmt":"2014-06-17T09:00:02","guid":{"rendered":"https:\/\/www.whizlabs.com\/?p=8043"},"modified":"2020-09-01T07:22:33","modified_gmt":"2020-09-01T07:22:33","slug":"implementing-threads-java","status":"publish","type":"post","link":"https:\/\/www.whizlabs.com\/blog\/implementing-threads-java\/","title":{"rendered":"Implementing Threads in Java"},"content":{"rendered":"<p>Before we get into thread implementation in Java, let us spend some time and understand the idea and concepts behind threads and concurrent programming.<\/p>\n<h3>What is Concurrency<\/h3>\n<p>Applications are expected to do more than one task at the same time in parallel. Applications which do more than one tasks at a time are called concurrent applications. An example of such concurrent software application is streaming audio application. It must read the digital audio from the network, decompress, manage playback and update the audio simultaneously.<\/p>\n<h3>Process and Thread<\/h3>\n<p>There are two basic units in the concurrent programming namely Process and Thread. In Java, the concurrent programming is implemented using Threads. Each operating system consists of many processes running to achieve different tasks. Each process has its own memory space. As a matter of fact, JVM (Java Virtual Machine) runs as a single process. A Process contains one more Threads. Each and every Thread which belongs to a Process can share Process\u2019s resources, memory and files.<\/p>\n<h3>Implementing Threads<\/h3>\n<p>Now, we have a good understanding of what is a process and thread. In Java, each thread is an instance of a class Thread. There are two ways to create a thread. The following two sections discuss about these two ways to create and start threads:<\/p>\n<h4>By Implementing Runnable Interface<\/h4>\n<p>The \u2018Runnable\u2019 interface contains a single method called \u2018run()\u2019 which contains the code to be executed in the thread. Once the thread instance is created and \u2018start()\u2019 method is called on the thread, JVM creates a thread and invokes &#8216;run()&#8217; method.<\/p>\n<p><code><br \/>\npublic class MyRunnable implements Runnable {<br \/>\npublic void run() {<br \/>\nSystem.out.println(\u201cMy first thread is running\u2026\u201d);<br \/>\n}<br \/>\npublic static void main(String\u2026 args) {<br \/>\nnew Thread(new MyRunnable()).start();<br \/>\n}<br \/>\n}<br \/>\n<\/code><\/p>\n<p>The above snippet of code creates a thread class by implementing \u2018Runnable\u2019 interface and by providing implementation for method \u2018run()\u2019. The \u2018run()\u2019 method will contain the execution logic for the thread to execute. After that, in the main() method we created an instance of the class which implements Runnable interface, and passed that instance to the new Thread object. Finally, we called \u2018start()\u2019 to start the thread execution.<\/p>\n<h5>Why calling <i>start()<i><\/i> method invokes <i>run()<\/i> method<\/i><\/h5>\n<p>In order to spawn a new thread, we need to call &#8216;start()&#8217; method. Calling &#8216;run()&#8217; method directly will execute current thread&#8217;s &#8216;run()&#8217; method. So for this reason we need to call &#8216;start()&#8217; method. Once the &#8216;start()&#8217; method is called, JVM creates a new thread instance and executes newly created thread&#8217;s &#8216;run()&#8217; method. Before calling &#8216;start()&#8217; method on a Thread instance, the thread will be in <i>new<\/i> state. This means that, we only have a Thread <i>object<\/i> not running thread. Once we call &#8216;start()&#8217; method on the thread instance, the following actions happen:<\/p>\n<ul>\n<li>New thread of execution starts<\/li>\n<li>Thread moves from new state to runnable state<\/li>\n<li>Thread&#8217;s &#8216;run()&#8217; method will be executed<\/li>\n<\/ul>\n<p>In fact, every Java program runs in a thread, we can call it the \u2018main\u2019 thread. In the above code example, we instantiated and started a thread from our main thread.<\/p>\n<h4>By Extending Thread Class<\/h4>\n<p>We can also create threads by extending Thread class and by overriding \u2018run()\u2019 method. This is because the Thread class itself implements Runnable interface. The following code sample shows how to create and start a thread by extending Thread class.<\/p>\n<p><code><br \/>\npublic class MyThread extends Thread {<br \/>\npublic void run() {<br \/>\nSystem.out.println(\u201cMy new thread from Thread class\u201d);<br \/>\n}<br \/>\npublic static void main(String\u2026 args) {<br \/>\nnew MyThread().start();<br \/>\n}<br \/>\n}<br \/>\n<\/code><\/p>\n<p>As we see the previous code example, we straightaway created our thread instance and started the thread by calling its \u2018start()\u2019 method.<\/p>\n<h4>Implementing Runnable vs. Extending Thread Class<\/h4>\n<p>As we already discussed we have two ways to create and start threads in Java. The following two points summarizes these two strategies and discusses which approach is most benefited.<\/p>\n<ul>\n<li>Thread creation by implementing Runnable interface abstracts thread management from the rest of our application. Once we have a thread instance we simply pass it to the executor which actually executes the thread.<\/li>\n<li>Thread creation by extending Thread class is probably simple to code. This way we can directly control and manage the thread creation. However, this approach has a drawback that, once a class extends Thread class, it cannot extend any other class. As we already know, Java allows only one class to extend as parent class.<\/li>\n<\/ul>\n<p>So the recommended way to create threads is by implementing Runnable interface. But, extending Thread class also fine provided that application requirements demands that. In terms of functionality and thread execution, there will not be any difference with respect to the above two approaches.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Before we get into thread implementation in Java, let us spend some time and understand the idea and concepts behind threads and concurrent programming. What is Concurrency Applications are expected to do more than one task at the same time in parallel. Applications which do more than one tasks at a time are called concurrent applications. An example of such concurrent software application is streaming audio application. It must read the digital audio from the network, decompress, manage playback and update the audio simultaneously. Process and Thread There are two basic units in the concurrent programming namely Process and Thread. [&hellip;]<\/p>\n","protected":false},"author":220,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[13],"tags":[967,1525],"class_list":["post-8043","post","type-post","status-publish","format-standard","hentry","category-java","tag-java-3","tag-threads"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"profile_24":false,"profile_48":false,"profile_96":false,"profile_150":false,"profile_300":false,"tptn_thumbnail":false,"web-stories-poster-portrait":false,"web-stories-publisher-logo":false,"web-stories-thumbnail":false},"uagb_author_info":{"display_name":"Aditi Malhotra","author_link":"https:\/\/www.whizlabs.com\/blog\/author\/aditi\/"},"uagb_comment_info":7,"uagb_excerpt":"Before we get into thread implementation in Java, let us spend some time and understand the idea and concepts behind threads and concurrent programming. What is Concurrency Applications are expected to do more than one task at the same time in parallel. Applications which do more than one tasks at a time are called concurrent&hellip;","_links":{"self":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/8043","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/users\/220"}],"replies":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/comments?post=8043"}],"version-history":[{"count":1,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/8043\/revisions"}],"predecessor-version":[{"id":76006,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/8043\/revisions\/76006"}],"wp:attachment":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/media?parent=8043"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/categories?post=8043"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/tags?post=8043"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}