{"id":22437,"date":"2021-05-20T04:27:40","date_gmt":"2021-05-20T04:27:40","guid":{"rendered":"https:\/\/cnsfly.com\/vytcdc\/?p=22437"},"modified":"2024-09-26T11:22:44","modified_gmt":"2024-09-26T11:22:44","slug":"multithreading-in-java","status":"publish","type":"post","link":"https:\/\/cnsfly.com\/vytcdc\/multithreading-in-java\/","title":{"rendered":"Multithreading in Java"},"content":{"rendered":"<p>How to create thread<\/p>\n<p>There are two ways to create a thread:<\/p>\n<p>By extending Thread class<br \/>\nBy implementing Runnable interface.<\/p>\n<figure id=\"attachment_23711\" aria-describedby=\"caption-attachment-23711\" style=\"width: 576px\" class=\"wp-caption alignnone\"><img fetchpriority=\"high\" decoding=\"async\" class=\"wp-image-23711 size-full\" src=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadimpl.png\" alt=\"Threads implementation in java\" width=\"576\" height=\"315\" srcset=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadimpl.png 576w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadimpl-300x164.png 300w\" sizes=\"(max-width: 576px) 100vw, 576px\" \/><figcaption id=\"caption-attachment-23711\" class=\"wp-caption-text\">Threads implementation in java<\/figcaption><\/figure>\n<p>Thread class:<\/p>\n<p>Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.<\/p>\n<h3><strong>By extending Thread class<\/strong><\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class Main {\r\npublic static void main(String[] args)  {\r\nHello h = new Hello();\r\nWorld w = new World();\r\nh.start();\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\nw.start();\r\n}\r\n}\r\nclass Hello extends Thread{\r\npublic void run()\r\n{\r\nfor (int i = 1; i &lt; 10; i++) {\r\nSystem.out.println(\"Hello\");\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\n}\r\n}\r\n}\r\nclass World extends Thread{\r\npublic void run()\r\n{\r\nfor (int i = 1; i &lt; 10; i++) {\r\nSystem.out.println(\"World\");\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\n}\r\n}\r\n}<\/pre>\n<h3>By implementing Runnable interface.<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class RunnableDemo {\r\npublic static void main(String[] args) throws InterruptedException {\r\nHello1 h = new Hello1();\r\nWorld1 w = new World1();\r\nThread t1 = new Thread(h);\r\nThread t2 = new Thread(w);\r\nt1.start();\r\nt2.start();\r\nSystem.out.println(t1.isAlive());\r\nt1.join();\r\nt2.join();\r\nSystem.out.println(\"Completed\");\r\nSystem.out.println(t1.isAlive());\r\n}\r\n}\r\nclass Hello1 implements Runnable{\r\npublic void run()\r\n{\r\nfor (int i = 1; i &lt; 10; i++) {\r\nSystem.out.println(\"Hello\");\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\n}\r\n}\r\n}\r\nclass World1 implements Runnable{\r\npublic void run()\r\n{\r\nfor (int i = 1; i &lt; 10; i++) {\r\nSystem.out.println(\"World\");\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\n}\r\n}\r\n}<\/pre>\n<h3>Creating Thread with Block<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class ThreadBlock {\r\npublic static void main(String[] args) throws InterruptedException {\r\nThread t1 = new Thread(new Runnable() {\r\n@Override\r\npublic void run() {\r\nfor(int i=0; i&lt;50;i++)\r\n{\r\nSystem.out.println(\"Hello\");\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\n}\r\n}\r\n});\r\nThread t2 = new Thread(new Runnable() {\r\n@Override\r\npublic void run() {\r\nfor(int i=0; i&lt;50;i++)\r\n{\r\nSystem.out.println(\"World\");\r\ntry {\r\nThread.sleep(200);\r\n} catch (InterruptedException e) {\r\ne.printStackTrace();\r\n}\r\n}\r\n}\r\n});\r\nt1.start();\r\n\/\/Thread.sleep(200);\r\nt2.start();\r\n}\r\n}<\/pre>\n<h3>Synchronized Demo<\/h3>\n<p>Synchronized block can be used to perform synchronization on any specific resource of the method.<\/p>\n<p>Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.<\/p>\n<p>If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.<\/p>\n<p>Points to remember for Synchronized block<\/p>\n<p>Synchronized block is used to lock an object for any shared resource.<\/p>\n<p>Scope of synchronized block is smaller than the method.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public class SyncDemo {\r\n\r\npublic static void main(String[] args) throws InterruptedException {\r\n\r\nWishtoSomeone ws = new WishtoSomeone();\r\n\r\nMyThread t1=new MyThread(ws,\"Abdul\");\r\n\r\nt1.start();\r\n\r\nMyThread t2=new MyThread(ws,\"Raju\");\r\n\r\nt2.start();\r\n\r\n}\r\n\r\n}\r\n\r\nclass WishtoSomeone{\r\n\r\npublic synchronized void wish(String name) {\r\n\r\nfor (int i = 0; i &lt; 10; i++) {\r\n\r\nSystem.out.print(\"Hello :\");\r\n\r\ntry {\r\n\r\nThread.sleep(200);\r\n\r\n} catch (InterruptedException e) {\r\n\r\ne.printStackTrace();\r\n\r\n}\r\n\r\nSystem.out.println(name);\r\n\r\n}\r\n\r\n}\r\n\r\n}\r\n\r\nclass MyThread extends Thread{\r\n\r\nWishtoSomeone ws;\r\n\r\nString name;\r\n\r\npublic MyThread(WishtoSomeone ws,String name) {\r\n\r\nthis.ws=ws;\r\n\r\nthis.name=name;\r\n\r\n}\r\n\r\npublic void run() {\r\n\r\nws.wish(name);\r\n\r\n}\r\n\r\n}<\/pre>\n<p><strong>Present in Object Class<\/strong><\/p>\n<p>Wait<br \/>\nNotify<br \/>\nNotifyAll<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-23712 size-full\" src=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/wait.jpg\" alt=\"\" width=\"561\" height=\"247\" srcset=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/wait.jpg 561w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/wait-300x132.jpg 300w\" sizes=\"(max-width: 561px) 100vw, 561px\" \/><\/p>\n<h3><strong>Waiting Thread in Java\u00a0<\/strong><\/h3>\n<p>Reason why these method not available in Thread class<\/p>\n<p>Our custom creation object example customer or student inside it wait and notify method are not available so it is there in object.<\/p>\n<p>Postman story<\/p>\n<p>Here t1 after calling wait method t1 goes to waiting state<\/p>\n<p>T2 will do some process on the object and once finish it will give notification means it will called notify method so that t1 will process on the same project.<\/p>\n<h3>Thread States<\/h3>\n<p><img decoding=\"async\" class=\"alignnone wp-image-23713 size-full\" src=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadstate.png\" alt=\"\" width=\"855\" height=\"437\" srcset=\"https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadstate.png 855w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadstate-300x153.png 300w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadstate-768x393.png 768w, https:\/\/cnsfly.com\/vytcdc\/wp-content\/uploads\/2021\/05\/threadstate-600x307.png 600w\" sizes=\"(max-width: 855px) 100vw, 855px\" \/><\/p>\n<p>Thread state in java<\/p>\n<p>If we called wait and notify method in non synchronized method then we get Exception illegalmonit or state exception<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">class Counter extends Thread{\r\n    \r\n    int total=0;\r\n    \r\n    public void run() {\r\n        \r\n        for(int i=0;i&lt;10;i++)\r\n        {\r\n            total = total+101;\r\n            \/\/result is 1000\r\n        }\r\n        synchronized(this)\r\n        {\r\n            this.notify();\r\n        }\r\n        \r\n        \r\n    }\r\n}\r\n\r\n\r\npublic class VarDemo {\r\n    public static void main(String[] args) throws InterruptedException {\r\n        Counter co = new Counter();\r\n        co.start();\r\n        \r\n        synchronized(co)\r\n\r\n        {\r\n            co.wait();\r\n        }\r\n        \r\n        System.out.println(co.total);\r\n        \r\n    }\r\n}<\/pre>\n<p>Note : Here we can call join method to get the same result but Recommended is wait method<\/p>\n<p>Why because<\/p>\n<p>for (int i = 0; i &lt;1000; i++)<\/p>\n<p>{<\/p>\n<p>total=total+1;<\/p>\n<p>}<\/p>\n<p>\/\/Thread A calling Notify method<\/p>\n<p>\/\/By calling notify method main thread get into running state<\/p>\n<p>this.notify();<\/p>\n<p>\/\/After for loop 10000 lines are there<\/p>\n<p>\/\/ then main thread wait until all lines execution finish<\/p>\n<p>&nbsp;<\/p>\n<p>Notify All<\/p>\n<p>Bus Example story narration<\/p>\n<p>Deadlock<\/p>\n<p>If two thread are waiting for each other that is known as deadlock<\/p>\n<p>1st thread is waiting for second thread activity and 2nd thread is waiting for first thread activity both are waiting is know as deadlock.<\/p>\n<p>Synchronized keyword is the only reason for deadlock hence need to take special care before using synchronized keyword.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How to create thread There are two ways to create a thread: By extending Thread class By implementing Runnable interface. Thread class:  Thread class provide constructors and methods to create<\/p>\n","protected":false},"author":1,"featured_media":23715,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[74],"tags":[25,26],"class_list":["post-22437","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android","tag-design","tag-development"],"_links":{"self":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22437","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/comments?post=22437"}],"version-history":[{"count":1,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22437\/revisions"}],"predecessor-version":[{"id":33848,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/posts\/22437\/revisions\/33848"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/media\/23715"}],"wp:attachment":[{"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/media?parent=22437"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/categories?post=22437"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cnsfly.com\/vytcdc\/wp-json\/wp\/v2\/tags?post=22437"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}