{"id":5473,"date":"2025-03-09T13:46:45","date_gmt":"2025-03-09T13:46:45","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=5473"},"modified":"2025-03-09T14:46:45","modified_gmt":"2025-03-09T14:46:45","slug":"simple-thread-programs","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/simple-thread-programs\/","title":{"rendered":"Simple Thread Programs"},"content":{"rendered":"<p><strong  class=\"ctaHeader3\">Simple Program to print numbers using threads<\/strong><br \/>\n<strong>NumberPrinter.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class NumberPrinter implements Runnable{\r\n    int number;\r\n    public NumberPrinter(int number){\r\n        this.number = number;\r\n    }\r\n\r\n    public void run(){\r\n        System.out.println(&quot;Printing Number from Thread &quot;+ this.number);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Main.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Main {\r\n    public static void main(String&#x5B;] args) {\r\n        for (int idx=1;idx&lt;=5;idx++){\r\n            Thread objthread = new Thread(new NumberPrinter(idx));\r\n            objthread.start();\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nPrinting Number from Thread 5\r\nPrinting Number from Thread 1\r\nPrinting Number from Thread 4\r\nPrinting Number from Thread 3\r\nPrinting Number from Thread 2\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\">Simple Program using Executor Service taking Runnable as Argument<\/strong><\/p>\n<section><a id=\"section1\"><\/a><\/section>\n<p>ExecutorService is a framework which allows to create thread. Threads can be created from FixedThreadPool,  CachedThreadPool and ScheduledThreadPool. submit() method takes runnable or callable object (Functional Interface Type) as argument. The Same code above can be rewritten as below<br \/>\n<strong>Main.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Main {\r\n    public static void main(String&#x5B;] args) throws Exception {\r\n        ExecutorService objExecService = Executors.newFixedThreadPool(2);\r\n\r\n        \/\/Lambda Expresssion passed as Argument as Runnable is FI\r\n        objExecService.submit(() -&gt; {\r\n            System.out.println(Thread.currentThread().getName());\r\n        });\r\n\r\n        objExecService.shutdown();\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\npool-1-thread-1\r\n<\/pre>\n<p><strong>Same code with Runnable instance passed as argument to submit<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n  .\r\n  . \r\n  \/\/Instance of Runnable passed as argument\r\n  HelloThread1 objHT1 = new HelloThread1();\r\n  objExecService.submit(objHT1);\r\n  .\r\n  .\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nHello World from Thread Name (pool-1-thread-1) using Runnable \r\n<\/pre>\n<p><strong>Same code with Runnable as Anonymous Class passed as argument<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nExecutorService exec = Executors.newFixedThreadPool(2);\r\n\r\n\/\/Instance of Runnable passed as Anonymous class\r\nexec.execute(new Runnable() {\r\n  public void run() {\r\n    System.out.println(&quot;Hello world&quot;);\r\n  }\r\n});\r\n\r\nexec.shutdown();\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\">Simple Program using Executor Service taking Callable as Argument<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Main {\r\n    public static void main(String&#x5B;] args) throws Exception {\r\n        ExecutorService objExecService = Executors.newFixedThreadPool(2);\r\n        Future&lt;String&gt; objFuture = objExecService.submit(new HelloThread2());\r\n        System.out.println(objFuture.get());\r\n        objExecService.shutdown();\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nHello World from Thread Name (pool-1-thread-1) using Callable\r\n<\/pre>\n<p><strong>Using Lambda Expression as Submi<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n.\r\n.\r\nExecutorService objExecService = Executors.newFixedThreadPool(2);\r\n\r\nFuture&lt;String&gt; objFuture = objExecService.submit(() -&gt; {\r\n  Thread.sleep(3000);\r\n  return Thread.currentThread().getName();\r\n});\r\n\r\nSystem.out.println(objFuture.get());\r\n.\r\n.\r\n<\/pre>\n<p><strong>The above could be rewritten in anonymous class as below<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nExecutorService objExecService = Executors.newFixedThreadPool(2);\r\n\r\nFuture&lt;String&gt; objFuture = objExecService.submit(new Callable&lt;String&gt;() {\r\n @Override\r\n public String call() throws Exception {\r\n   Thread.sleep(3000);\r\n   return Thread.currentThread().getName();\r\n }\r\n});\r\n\r\nSystem.out.println(objFuture.get());\r\nobjExecService.shutdown();\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\">Program for Creating Thread Pool and executing Task<\/strong><\/p>\n<section><a id=\"section2\"><\/a><\/section>\n<p><strong>ThreadPoolExample.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class ThreadPoolExample {\r\n    public static void main(String args&#x5B;]) {\r\n       ExecutorService service = Executors.newFixedThreadPool(10); \/\/create 10 worker threads in Thread Pool\r\n       for (int i =0; i&lt;100; i++){\r\n           service.submit(new Task(i)); \/\/submit that to be done \r\n       }\r\n       service.shutdown();\r\n    }  \r\n}\r\n<\/pre>\n<p><strong>Task.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nfinal class Task implements Runnable {\r\n    private int taskId;  \r\n    public Task(int id){\r\n        this.taskId = id;\r\n    }\r\n  \r\n    @Override\r\n    public void run() {\r\n        System.out.println(&quot;Task ID : &quot; + this.taskId +&quot; performed by &quot; \r\n                           + Thread.currentThread().getName());\r\n    }  \r\n}\r\n<\/pre>\n<pre>\r\nTask ID : 0 performed by pool-1-thread-1\r\nTask ID : 3 performed by pool-1-thread-4\r\nTask ID : 2 performed by pool-1-thread-3\r\nTask ID : 1 performed by pool-1-thread-2\r\nTask ID : 5 performed by pool-1-thread-6\r\nTask ID : 4 performed by pool-1-thread-5\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Simple Program to print numbers using threads NumberPrinter.java public class NumberPrinter implements Runnable{ int number; public NumberPrinter(int number){ this.number = number; } public void run(){ System.out.println(&quot;Printing Number from Thread &quot;+ this.number); } } Main.java public class Main { public static void main(String&#x5B;] args) { for (int idx=1;idx&lt;=5;idx++){ Thread objthread = new Thread(new NumberPrinter(idx)); objthread.start(); }&hellip; <a href=\"https:\/\/codethataint.com\/blog\/simple-thread-programs\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[364],"tags":[],"class_list":["post-5473","post","type-post","status-publish","format-standard","hentry","category-examples"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/5473","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=5473"}],"version-history":[{"count":3,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/5473\/revisions"}],"predecessor-version":[{"id":5480,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/5473\/revisions\/5480"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=5473"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=5473"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=5473"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}