{"id":79263,"date":"2020-07-01T09:00:22","date_gmt":"2020-07-01T03:30:22","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=79263"},"modified":"2020-07-01T09:00:22","modified_gmt":"2020-07-01T03:30:22","slug":"runnable-interface-in-java","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/","title":{"rendered":"Runnable Interface in Java to Create Threads"},"content":{"rendered":"<p>In this article, we will learn the Runnable interface in Java, which is a core element of Java when working with threads. Any class in Java that intends to execute threads must implement the Runnable interface.<\/p>\n<p>In this article, we will provide you a complete insight into the Runnable interface of Java, along with the examples. So, let us start the tutorial with the introduction to the Runnable interface in Java.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Runnable-Interface-in-Java-tv.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-79333\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Runnable-Interface-in-Java-tv.jpg\" alt=\"Runnable Interface in Java\" width=\"1200\" height=\"628\" \/><\/a><\/p>\n<h3>Runnable Interface in Java<\/h3>\n<p>Runnable interface of Java is present in the java.lang package. It is a type of functional interface that provides a primary template for objects that we want to implement using threads.<\/p>\n<p>We know that there are two ways to start a new Thread: Extending the Thread class and implementing the Runnable interface. There is no need to extend or subclass a Thread class when we can perform a task by overriding only the run() method of the Runnable interface.<\/p>\n<p>Hence the Runnable interface provides a way for a class to be active without extending the Thread class. We need to instantiate an object of the Thread and pass it in as the target.<\/p>\n<p>We mostly implement the Runnable interface when using no other method than the run() method. The Runnable interface defines only one method run() with no arguments and holds the code that needs to be executed by the thread.<\/p>\n<p>Thus the classes implementing the Runnable interface need to override the run() method.<\/p>\n<h3>run() Method of Runnable Interface<\/h3>\n<p>The runnable interface has an undefined method run(). run() has void as return type, and it takes in no arguments. Below table shows the summary of the run() method:<\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Method<\/b><\/td>\n<td><b>Description<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">public void run()<\/span><\/td>\n<td><span style=\"font-weight: 400\">The run() method takes no arguments. When the object of a class that implements the Runnable interface creates a thread, then the run() method is invoked in the thread, and this method executes separately.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Steps to Create New Thread using Runnable Interface<\/h3>\n<p>There are following steps to create a new thread using the Runnable interface:<\/p>\n<p>1. The first step is to create a Java class that implements the Runnable interface.<br \/>\n2. The second step is to override the run() method of the Runnable() interface in the class.<br \/>\n3. Now, pass the Runnable object as a parameter to the constructor of the object of the Thread class while creating it. Now, this object is capable of executing the Runnable class.<br \/>\n4. Finally, invoke the start method of the Thread object.<\/p>\n<h3>Implementing Runnable Interface<\/h3>\n<p>Implementing a Runnable interface is the easiest way to create a thread. We can create a thread on any object by implementing the Runnable interface. To implement a Runnable, we only have to implement the run() method.<\/p>\n<p>In this method, there is a code that we want to execute on a concurrent thread. We can use variables, instantiate classes, and perform an action in the run() method the same way the main thread does. The thread remains active until the return of this method.<\/p>\n<p>The run() method establishes an entry point to a new thread.<\/p>\n<p><strong>Code to implement Runnable interface in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.runnableinterface;\npublic class RunnableDemo {\n  public static void main(String[] args) {\n    System.out.println(\"From main() method: \" + Thread.currentThread().getName());\n    System.out.println(\"Creating Runnable Instance\");\n    Runnable runnable = new Runnable() {@Override\n      public void run() {\n        System.out.println(\"From run() method: \" + Thread.currentThread().getName());\n      }\n    };\n\n    System.out.println(\"Creating a Thread Instance\");\n    Thread thread = new Thread(runnable);\n\n    System.out.println(\"Launching the thread...\");\n    thread.start();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">From main() method: main<br \/>\nCreating Runnable Instance<br \/>\nCreating a Thread Instance<br \/>\nLaunching the thread&#8230;<br \/>\nFrom run() method: Thread-0<\/div>\n<h3>What happens when Runnable encounters an exception?<\/h3>\n<p>The Runnable interface can not throw checked exceptions but it can throw RuntimeException from the run() method. The exception handler of the thread handles the uncaught exceptions if JVM is unable to handle or catch them. It also prints the stack trace and terminates the program flow.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.io.FileNotFoundException;\npublic class RunnableDemo {\n  public static void main(String[] args) {\n    System.out.println(\"The main thread is: \" + Thread.currentThread().getName());\n    Thread t1 = new Thread(new RunnableDemo().new RunnableImplementation());\n    t1.start();\n  }\n  private class RunnableImplementation implements Runnable {\n    public void run() {\n      System.out.println(Thread.currentThread().getName() + \", executing the run() method!\");\n      try {\n        throw new FileNotFoundException();\n      }\n      catch(FileNotFoundException e) {\n        System.out.println(\"Must catch an exception here!\");\n        e.printStackTrace();\n      }\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The main thread is: main<br \/>\nThread-0, executing the run() method!<br \/>\nMust catch an exception here!<br \/>\njava.io.FileNotFoundException<br \/>\nat RunnableDemo$RunnableImplementation.run(Example.java:21)<br \/>\nat java.lang.Thread.run(Thread.java:748)<\/div>\n<p>The above output shows that Runnable class can not throw checked exceptions which is FileNotFoundException in this case. It should handle the checked exceptions in the run() method but JVM automatically handles the RuntimeExceptions.<\/p>\n<h3>Use of Runnable class in network programming<\/h3>\n<p>The Runnable class can also perform multi-thread programming, especially on the server-side because a server may be getting several requests from different clients. We use multi-thread programming to tackle this in a fast and resource-efficient way.<\/p>\n<p><strong>Example of a networking program using Runnable:<\/strong><\/p>\n<p>The following program shows a server program which creates a thread, then creates a socket and waits for a client to connect to it and asks for an input string-<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.io. * ;\nimport java.net. * ;\npublic class Example {\n  public static void main(String[] args) {\n    new Thread(new SimpleServer()).start();\n  }\n  static class SimpleServer implements Runnable {@Override\n    public void run() {\n      ServerSocket serverSocket = null;\n      while (true) {\n        try {\n          serverSocket = new ServerSocket(3333);\n          Socket clientSocket = serverSocket.accept();\n\n          BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));\n          System.out.println(\"Client said :\t\" + inputReader.readLine())\n        }\n        catch(IOException e) {\n          e.printStackTrace();\n        }\n        finally {\n          try {\n            serverSocket.close();\n          }\n          catch(IOException e) {\n            e.printStackTrace();\n          }\n        }\n      }\n    }\n  }\n}<\/pre>\n<h3>Thread class vs. Runnable interface<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Thread-class-vs-Runnable-interface-in-java-tv.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-79332\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Thread-class-vs-Runnable-interface-in-java-tv.jpg\" alt=\"Thread class vs Runnable interface in java \" width=\"548\" height=\"588\" \/><\/a><\/p>\n<p>There are many differences between the Thread class and Runnable interface on the basis of their performance, memory usage, and composition.<\/p>\n<ul>\n<li>There is the overhead of additional methods by extending the thread class. They consume excess or indirect memory, computation time, or other resources.<\/li>\n<li>As we can only extend one class in Java, therefore, if we extend Thread class, then we can not extend any other class. Therefore, we should prefer to implement the Runnable interface to create a thread.<\/li>\n<li>The Runnable interface makes the code more flexible. And, if we are extending a thread, then our code will only be in a thread. Whereas, if we implement the runnable interface, we can pass it in various executor services or to the single-threaded environment.<\/li>\n<li>The maintenance of the code becomes easy if we implement the Runnable interface.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>Here, we come to the end of the article. We learned about the Runnable interface in Java which is very important in creating threads in Java. It is more preferable as compared to the Thread class in Java when creating the threads.<\/p>\n<p>We discussed the steps to create the thread using the Runnable interface in Java. We hope you might have understood the concept of the Runnable interface in Java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn the Runnable interface in Java, which is a core element of Java when working with threads. Any class in Java that intends to execute threads must implement the&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79333,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2969,2970,2971,2972],"class_list":["post-79263","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-runnable","tag-java-runnable-example","tag-java-runnable-interface","tag-runnable-interface-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Runnable Interface in Java to Create Threads - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about runnable interface in java with examples, run() method, Implementing Runnable interface, Thread class vs. Runnable interface\" \/>\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\/runnable-interface-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Runnable Interface in Java to Create Threads - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about runnable interface in java with examples, run() method, Implementing Runnable interface, Thread class vs. Runnable interface\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/\" \/>\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=\"2020-07-01T03:30:22+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Runnable-Interface-in-Java-tv.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\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=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Runnable Interface in Java to Create Threads - TechVidvan","description":"Learn about runnable interface in java with examples, run() method, Implementing Runnable interface, Thread class vs. Runnable interface","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\/runnable-interface-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Runnable Interface in Java to Create Threads - TechVidvan","og_description":"Learn about runnable interface in java with examples, run() method, Implementing Runnable interface, Thread class vs. Runnable interface","og_url":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-07-01T03:30:22+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Runnable-Interface-in-Java-tv.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Runnable Interface in Java to Create Threads","datePublished":"2020-07-01T03:30:22+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/"},"wordCount":949,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Runnable-Interface-in-Java-tv.jpg","keywords":["java runnable","java runnable example","java runnable interface","Runnable Interface in Java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/","url":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/","name":"Runnable Interface in Java to Create Threads - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Runnable-Interface-in-Java-tv.jpg","datePublished":"2020-07-01T03:30:22+00:00","description":"Learn about runnable interface in java with examples, run() method, Implementing Runnable interface, Thread class vs. Runnable interface","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Runnable-Interface-in-Java-tv.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Runnable-Interface-in-Java-tv.jpg","width":1200,"height":628,"caption":"Runnable Interface in Java"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/runnable-interface-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Runnable Interface in Java to Create Threads"}]},{"@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\/79263","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=79263"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79263\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79333"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=79263"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=79263"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=79263"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}