Title: Java Runnable Example - Java Code Geeks
Open Graph Title: Java Runnable Example - Java Code Geeks
Description: In this example, we will take a look into the Runnable interface in Java, and how it can be used in association with the Thread class to create and
Open Graph Description: In this example, we will take a look into the Runnable interface in Java, and how it can be used in association with the Thread class to create and
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-runnable-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-runnable-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-runnable-example/"},"author":{"name":"Ilias Koutsakis","@id":"https://examples.javacodegeeks.com/#/schema/person/fb0976e76a1d563d8abc790ed9a1871c"},"headline":"Java Runnable Example","datePublished":"2014-07-04T08:00:35+00:00","dateModified":"2020-07-31T08:55:35+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-runnable-example/"},"wordCount":935,"commentCount":3,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-runnable-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","keywords":["runnable","thread"],"articleSection":["Runnable"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-runnable-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-runnable-example/","url":"https://examples.javacodegeeks.com/java-runnable-example/","name":"Java Runnable Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-runnable-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-runnable-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2014-07-04T08:00:35+00:00","dateModified":"2020-07-31T08:55:35+00:00","description":"In this example, we will take a look into the Runnable interface in Java, and how it can be used in association with the Thread class to create and","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-runnable-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-runnable-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-runnable-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-runnable-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"lang","item":"https://examples.javacodegeeks.com/category/java-development/core-java/lang/"},{"@type":"ListItem","position":5,"name":"Runnable","item":"https://examples.javacodegeeks.com/category/java-development/core-java/lang/runnable/"},{"@type":"ListItem","position":6,"name":"Java Runnable Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/fb0976e76a1d563d8abc790ed9a1871c","name":"Ilias Koutsakis","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2014/06/Ilias-Koutsakis-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2014/06/Ilias-Koutsakis-96x96.jpg","caption":"Ilias Koutsakis"},"description":"Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.","sameAs":["http://www.javacodegeeks.com/"],"url":"https://examples.javacodegeeks.com/author/ilias-koutsakis/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}},{"@type":"ListItem","position":4,"item":{"name":"lang","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/lang\/"}},{"@type":"ListItem","position":5,"item":{"name":"Runnable","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/lang\/runnable\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2014-07-04T11:00:35+03:00","datePublished":"2014-07-04T11:00:35+03:00","dateModified":"2020-07-31T11:55:35+03:00","headline":"Java Runnable Example","name":"Java Runnable Example","keywords":"runnable,thread","url":"https:\/\/examples.javacodegeeks.com\/java-runnable-example\/","description":"In this example, we will take a look into the Runnable interface in Java, and how it can be used in association with the Thread class to create and execute new threads in your program. We will also tr","copyrightYear":"2014","articleSection":"Runnable","articleBody":"\nIn this example, we will take a look into the Runnable interface in Java, and how it can be used in association with the Thread class to create and execute new threads in your program. We will also try to explain what a Runnable is and what's the\u00a0difference from Thread, as well as take a look into the different ways that you can implement\u00a0Runnable in your code.\n\n\n\n1. Runnables and Threads\n\n\n\nLet's start by talking about a very common confusion in Java. Runnables are NOT Threads. The Runnable interface is used to define a certain task that we want to execute, and the whole implementation of this task is inside its only method, run() (which accepts no arguments). The Runnable class by itself does not create a separate thread, because this is what Thread actually does.\n\n\n\nThread is used to create a new execution path (a new thread), separate from the main program. By providing a Runnable as an argument to a Thread constructor, you are essentially giving access of the Runnable's task (defined in the run() method), to a new Thread object. At any time during your program, you can start the new thread, by using Thread.start() and the Runnable's code will start running.\n\n\n\n2. Why use Runnable?\n\n\n\nAlthough you have the ability to create new threads by using just the Thread class, which by itself implements the Runnable interface, the suggested and much more accepted approach is to use Runnable for all the logic that we want to provide for our threads. There are certain reasons for that:\n\n\n\nModularity: When you run a thread and it finishes running, there is no way to restart it. This could lead to a lot of code duplication in case of multithreading, where you need a certain task to run a number of times. Fortunately, you can create a Runnable instance which can be reused in any number of threads.Ease of use: Runnable only has one method, public void run(). It accepts no arguments and is as simple as possible. Thread has many methods that need to be taken into account making it very cumbersome to work with, and the extra overhead is always an issue.Inheritance: More often than not, you will have to use additional classes (through inheritance) to extend the functionality of your Runnable object. Java does not support multiple inheritance, so it is much more convenient to create a new class which just implements Runnable (and allows to extend another class) than creating a new class that extends Thread and prevents you from inheriting anything else.\n\n\n\n3. Runnable implementation and example\n\n\n\nThere are two ways to implement a Runnable in Java. Let's take a quick look into them:\n\n\n\nInheritance: You can create a class which implements the Runnable interface. You will be forced to implement the run() method, which contains the logic\/code of the task, and instantiate it in the standard Java way. You can use pass this as an argument to a Thread instance, as explained above.Anonymous inner class: In some cases you need to run a small snippet of only a few lines of code. In that case, you can always create a new anonymous inner class inside the Thread constructor and implement the run() method there as well. This is of course not modular, and you cannot reuse that code.\n\n\n\nLet's take a look at the code and see both of these ways at work!\n\n\n\nMyRunnableImplementation.java\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n\n\n\npackage com.javacodegeeks.runnableexample;\n \npublic class MyRunnableImplementation implements Runnable {\n \n \/\/ We are creating anew class that implements the Runnable interface,\n \/\/ so we need to override and implement it's only method, run().\n @Override\n public void run() {\n \n \/\/ We are creating a simple loop which will run and allow us to take\n \/\/ a look into how the different threads run.\n for (int i = 0; i < 5; i++) {\n \n \/\/ Thread.currentThread().getName() is used to get the name of the \n \/\/ currently running thread. We can provide a name, if we create\n \/\/ the thread ourselves, else it will be given one from the JVM.\n System.out.println(Thread.currentThread().getName() +\n \"\\twith Runnable: MyRunnableImplementation runs...\" + i);\n }\n }\n}\n\n\n\n\n\n\n\n\n\n\nAs you can see, we create a class that implements the Runnable interface. In the main program, we will instantiate this class and pass it as an argument to a Thread constructor, which will run the task, which in this context is the loop.\n\n\n\nRunnableExampleMain.java\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n\n\n\npackage com.javacodegeeks.runnableexample;\n \n \npublic class RunnableExampleMain {\n \n public static void main(String[] args) {\n System.out.println(\"Executing program...\");\n \n \/\/ Create a new instance of our class that implements the Runnable interface.\n \/\/ This class can be provided as an argument to a Thread instance.\n MyRunnableImplementation r = new MyRunnableImplementation();\n \n \/\/ Create a new Thread instance, provide the task that we want to run\n \/\/ (by providing the Runnable as an argument) and give the thread a name.\n \/\/ Now we can use Thread.start() to run it!\n Thread thread1 = new Thread(r, \"Thread 1\");\n thread1.start();\n \n \/\/ We are creating a second thread. Take notice that we are\n \/\/ providing the same Runnable, so this thread will run the same task\n \/\/ as the first one.\n Thread thread2 = new Thread(r, \"Thread 2\");\n thread2.start();\n \n \/\/ Create a thread and provide the Runnable argument as an anonymous inner class.\n \/\/ Since we are creating the class \"on the spot\", we need to provide the implementation\n \/\/ of the run() method here.\n \/\/ This way is faster and more compact, but it lacks reusability.\n Thread thread3 = new Thread(new Runnable() {\n @Override\n public void run() {\n \n \/\/ We are doing the same thing as with the MyRunnableImplementation class\n for (int i = 0; i < 5; i++) {\n System.out.println(Thread.currentThread().getName() +\n \"\\twith Runnable: Inner class Runnable runs...\" + i);\n }\n }\n }, \"Thread 3\");\n thread3.start();\n }\n}\n\n\n\n\n\n\n\n\n\n\nTake notice here, that we can use the same Runnable on more than one Thread, without an issue. Also, we can implement the Runnable anonymously inside the constructor.\n\n\n\n3.1 Java Runnable Example - Output\n\n\n\nWe have to take into consideration the fact that we are talking about different threads here, which are unpredictable by definition. Depending on the JVM implementation and the running platform's architecture, the threads can run in any order. In our example specifically, you can see different output variations, because although the threads run concurrently (so when you invoke Thread.start() a new thread starts running in parallel to your main program), they all have the task to print something to the standard output, and we have no way of knowing which thread will use the output at any given time.\n\n\n\nLet's take a look at two different runs, where we can easily see which thread runs and which Runnable they are using:\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n\n\n\nExecuting program...\nThread 1 with Runnable: MyRunnableImplementation runs...0\nThread 1 with Runnable: MyRunnableImplementation runs...1\nThread 1 with Runnable: MyRunnableImplementation runs...2\nThread 1 with Runnable: MyRunnableImplementation runs...3\nThread 1 with Runnable: MyRunnableImplementation runs...4\nThread 2 with Runnable: MyRunnableImplementation runs...0\nThread 2 with Runnable: MyRunnableImplementation runs...1\nThread 2 with Runnable: MyRunnableImplementation runs...2\nThread 2 with Runnable: MyRunnableImplementation runs...3\nThread 2 with Runnable: MyRunnableImplementation runs...4\nThread 3 with Runnable: Inner class Runnable runs...0\nThread 3 with Runnable: Inner class Runnable runs...1\nThread 3 with Runnable: Inner class Runnable runs...2\nThread 3 with Runnable: Inner class Runnable runs...3\nThread 3 with Runnable: Inner class Runnable runs...4\n\n\n\n\n\n\n\n\n\n\nPretty standard, the output is what someone would possibly expect. Take notice that the two first threads used the same instance of MyRunnableImplementation with no issues, while the third one used the inner class. However, after running it again for a couple of times, we got this output:\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n12\n13\n14\n15\n16\n\n\n\nExecuting program...\nThread 1 with Runnable: MyRunnableImplementation runs...0\nThread 1 with Runnable: MyRunnableImplementation runs...1\nThread 1 with Runnable: MyRunnableImplementation runs...2\nThread 1 with Runnable: MyRunnableImplementation runs...3\nThread 1 with Runnable: MyRunnableImplementation runs...4\nThread 3 with Runnable: Inner class Runnable runs...0\nThread 3 with Runnable: Inner class Runnable runs...1\nThread 3 with Runnable: Inner class Runnable runs...2\nThread 2 with Runnable: MyRunnableImplementation runs...0\nThread 2 with Runnable: MyRunnableImplementation runs...1\nThread 3 with Runnable: Inner class Runnable runs...3\nThread 3 with Runnable: Inner class Runnable runs...4\nThread 2 with Runnable: MyRunnableImplementation runs...2\nThread 2 with Runnable: MyRunnableImplementation runs...3\nThread 2 with Runnable: MyRunnableImplementation runs...4\n\n\n\n\n\n\n\n\n\n\nPretty cool, right? Well, yes, but threads can sometimes cause a real headache, and in many cases, you need to know in which order they run. Luckily, Java contains ways of achieving synchronization and scheduling, which are out of the scope of this tutorial.\n\n\n\n4. Download the source code\n\n\n\nIn this example, we learned the Runnable interface in Java, and how it can be used in association with the Thread class to create and execute new threads in your program.\n\n\n\nThis was an example of the Runnable interface in Java.\nDownload\nDownload the Eclipse project of this tutorial here: Java Runnable Example\n\n\n\nLast updated on Apr. 28th, 2020\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-runnable-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Ilias Koutsakis","url":"https:\/\/examples.javacodegeeks.com\/author\/ilias-koutsakis\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2014-07-04T08:00:35+00:00 |
| article:modified_time | 2020-07-31T08:55:35+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Ilias Koutsakis |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Ilias Koutsakis |
| twitter:label2 | Est. reading time |
| twitter:data2 | 10 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1