{"id":88626,"date":"2024-01-22T18:00:23","date_gmt":"2024-01-22T12:30:23","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88626"},"modified":"2024-01-22T18:00:23","modified_gmt":"2024-01-22T12:30:23","slug":"java-thread-run-method-with-examples","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/","title":{"rendered":"Java Thread run() Method with Examples"},"content":{"rendered":"<p>In Java, you can call the run() method directly on a class that implements the Runnable interface. However, it&#8217;s important to understand the distinction between calling run() and start() methods on a thread.<\/p>\n<h2>Calling run() Method<\/h2>\n<p>When you call the run() method directly on a class that implements Runnable, it simply runs the method in the same calling thread, and there is no separate thread of execution. The run() method behaves like any other method call, and the execution is sequential.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class TechVidvanrunmethodDemo {\n    public static void main(String[] args) {\n        MyRunnable r = new MyRunnable();\n    \t\/\/ Calling the run() method directly\n    \tr.run();\n    }\n}\nclass MyRunnable implements Runnable {\n    public void run() {\n        System.out.println(\"TechVidvan-Thread is running\");\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>TechVidvan-<\/strong>Thread is running<\/p>\n<h3>Calling start() Method:<\/h3>\n<p>To create a new thread and execute the run() method in a separate thread of execution, you need to call the start() method on a Thread object. The start() method internally calls the run() method in a new thread, allowing concurrent execution.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class Main {\n    public static void main(String[] args) {\n        MyRunnable r = new MyRunnable();\n    \tThread t = new Thread(r);\n    \t\/\/ Starting a new thread and calling the run() method in that thread\n        t.start();\n    }\n}\n \nclass MyRunnable implements Runnable {\n    public void run() {\n        System.out.println(\"TechVidvan-Thread is running\");\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>TechVidvan-<\/strong>Thread is running<\/p>\n<h3>Overloading the run() method:<\/h3>\n<p><strong>Example code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class BaseRunnable implements Runnable {\n    @Override\n    public void run() {\n        System.out.println(\"BaseRunnable's run() method\");\n    }\n    public void run(String message) {\n        System.out.println(\"CustomRunnable's overloaded run(): \" + message);\n    }\n}\nclass DataFlair{\n    public static void main(String[] args) {\n        BaseRunnable baseRunnable = new BaseRunnable();\n        baseRunnable.run(); \/\/ Output: BaseRunnable's run() method\n        baseRunnable.run(\"Techvidvan run() example\"); \/\/ Output: BaseRunnable's overloaded run(): Techvidvan run() example\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>BaseRunnable&#8217;s run() method<\/p>\n<p><strong>CustomRunnable&#8217;s overloaded run():<\/strong> Techvidvan run() example<\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p>In the above code, the run() method is explicitly called, and the overloaded run(String message) method is also explicitly called. The reason why the run() method is called explicitly is because it&#8217;s not automatically called by the Java runtime when an instance of Runnable is used with the Thread class. Instead, the run() method is intended to be invoked by the Thread class when the thread is started.<\/p>\n<h3>Calling run() Multiple times:<\/h3>\n<p>When you call the run() method on an object of a class that implements the Runnable interface, the method&#8217;s code is executed in the current thread, just like any other regular method call. There is no new thread created.<\/p>\n<p><strong>Example Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MyRunnable implements Runnable {\n    @Override\n    public void run() {\n        for(int i=1;i&lt;6;i++) {\n            System.out.println(\"Running \" + i + \" time\");\n        }\n    }\n}\nclass DataFlair{\n    public static void main(String[] args) {\n        MyRunnable myRunnable = new MyRunnable();\n        myRunnable.run(); \/\/ This does not create a new thread.\n        myRunnable.run(); \/\/ It just runs the code sequentially.\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Running 1 time<\/p>\n<p>Running 2 time<\/p>\n<p>Running 3 time<\/p>\n<p>Running 4 time<\/p>\n<p>Running 5 time<\/p>\n<p>Running 1 time<\/p>\n<p>Running 2 time<\/p>\n<p>Running 3 time<\/p>\n<p>Running 4 time<\/p>\n<p>Running 5 time<\/p>\n<p>If you do not override the run() method when implementing the Runnable interface, you will still have a class that compiles successfully. However, when you create an instance of this class and pass it to a Thread object to start a new thread, the new thread will have no specific code to execute. Here&#8217;s what happens:<\/p>\n<h3>Without Overriding run():<\/h3>\n<p>If you don&#8217;t provide your own implementation of the run() method in the class that implements Runnable, the default run() method of the Runnable interface will be inherited and used. The default run() method does nothing; it&#8217;s an empty method. So, when you start a thread using an instance of your class, the thread will execute the default, empty run() method, and the thread will complete immediately.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<p><strong>Let&#8217;s say you have the following class that implements Runnable without overriding the run() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MyRunnable implements Runnable {\n    \/\/ No custom implementation of run() here\n}<\/pre>\n<p><strong>And you attempt to use it like this:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class Main {\n    public static void main(String[] args) {\n        MyRunnable myRunnable = new MyRunnable();\n        Thread thread = new Thread(myRunnable);\n        thread.start(); \/\/ The thread starts but doesn't execute any specific code.\n    }\n}<\/pre>\n<p>In this case, the thread will start but immediately finish because the default run() method doesn&#8217;t contain any meaningful code.<\/p>\n<p>To achieve actual concurrent execution and customize what a thread does, you must override the run() method in your class that implements the Runnable interface. This allows you to provide specific behavior that the new thread will execute when started.<\/p>\n<h3>Summary<\/h3>\n<p>In summary, calling the run() method directly on a class that implements Runnable runs the method in the same thread, while calling the start() method on a Thread object creates a new thread and executes the run() method concurrently in that new thread. For true multithreading and parallel execution, use the start() method to create new threads and execute the run() method in separate.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, you can call the run() method directly on a class that implements the Runnable interface. However, it&#8217;s important to understand the distinction between calling run() and start() methods on a thread. Calling&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":89063,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[5329,5330,5331,5332,327,250,5333],"class_list":["post-88626","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-calling-run-method","tag-calling-thread-run-method","tag-java-calling-run-method","tag-java-thread-run-method","tag-java-tutorials","tag-learn-java","tag-thread-run-method-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Thread run() Method with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"The Java thread run() method behaves like any other method call, and the execution is sequential. Also, execute the run() method separately.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Thread run() Method with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"The Java thread run() method behaves like any other method call, and the execution is sequential. Also, execute the run() method separately.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-01-22T12:30:23+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Thread run() Method with Examples - TechVidvan","description":"The Java thread run() method behaves like any other method call, and the execution is sequential. Also, execute the run() method separately.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/","og_locale":"en_US","og_type":"article","og_title":"Java Thread run() Method with Examples - TechVidvan","og_description":"The Java thread run() method behaves like any other method call, and the execution is sequential. Also, execute the run() method separately.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2024-01-22T12:30:23+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Thread run() Method with Examples","datePublished":"2024-01-22T12:30:23+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/"},"wordCount":579,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#primaryimage"},"thumbnailUrl":"","keywords":["calling run() method","calling thread run method","java calling run() method","java thread run method","java tutorials","Learn Java","thread run method in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/","url":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/","name":"Java Thread run() Method with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#primaryimage"},"thumbnailUrl":"","datePublished":"2024-01-22T12:30:23+00:00","description":"The Java thread run() method behaves like any other method call, and the execution is sequential. Also, execute the run() method separately.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-thread-run-method-with-examples\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Thread run() Method with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88626","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=88626"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88626\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=88626"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88626"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88626"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}