{"id":5030,"date":"2024-03-30T12:53:49","date_gmt":"2024-03-30T12:53:49","guid":{"rendered":"https:\/\/codethataint.com\/blog\/?p=5030"},"modified":"2024-03-31T11:00:04","modified_gmt":"2024-03-31T11:00:04","slug":"threads-and-states","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/threads-and-states\/","title":{"rendered":"Threads and States"},"content":{"rendered":"<ol>\n<li><strong>NEW<\/strong> \u2013 a newly created thread that has not yet started the execution<\/li>\n<li><strong>RUNNABLE<\/strong> \u2013 either running or ready for execution but it\u2019s waiting for resource allocation<\/li>\n<li><strong>BLOCKED<\/strong> \u2013 waiting to acquire a monitor lock to enter or re-enter a synchronized block\/method<\/li>\n<li><strong>WAITING<\/strong> \u2013 waiting for some other thread to perform a particular action without any time limit<\/li>\n<li><strong>TIMED_WAITING<\/strong> \u2013 waiting for some other thread to perform a specific action for a specified period<\/li>\n<li><strong>TERMINATED<\/strong> \u2013 has completed its execution<\/li>\n<\/ol>\n<p><strong  class=\"ctaHeader3\">NEW <\/strong>Thread (or a Born Thread) is a thread that\u2019s been created but not yet started.<br \/>\nIt remains in this state until we start it using the start() method<\/p>\n<p><strong>NewState.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class NewState implements Runnable{\r\n    public void run(){\r\n        System.out.println(&quot;I am in new State&quot;);\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) throws InterruptedException {\r\n       Thread objThread = new Thread(new NewState());\r\n       System.out.println(objThread.getState());\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nNEW\r\n<\/pre>\n<p><strong class=\"ctaHeader3\">Runnable<\/strong> When we\u2019ve created a new thread and called the start() method on that, it\u2019s moved from NEW to RUNNABLE state. Threads in this state are either running or ready to run, but<br \/>\nthey\u2019re waiting for resource allocation from the system. In a multi-threaded environment, the Thread-Scheduler (which is part of JVM) allocates a fixed amount of time to each thread. So it runs for a particular amount of time, then leaves the control to other RUNNABLE threads.<\/p>\n<p><strong>RunnableState .java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class RunnableState implements Runnable{\r\n    public void run(){\r\n        System.out.println(&quot;I would be in Runnable State&quot;);\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) throws InterruptedException {\r\n       Thread objRThread = new Thread(new RunnableState());\r\n       objRThread.start();\r\n       System.out.println(objRThread.getState());\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nRUNNABLE\r\nI would be in Runnable State\r\n<\/pre>\n<p>This is the state of a dead thread. It\u2019s in the <strong class=\"ctaHeader3\">TERMINATED<\/strong> state when it has either finished execution or was terminated abnormally.<br \/>\n<strong>TerminatedState.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class TerminatedState implements Runnable{\r\n    public void run(){\r\n        Thread objNewState = new Thread(new NewState());\r\n        objNewState.start();\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) throws InterruptedException {\r\n       Thread objTState = new Thread(new TerminatedState());\r\n       objTState.start();\r\n       objTState.sleep(1000);\r\n       System.out.println(&quot;T1 : &quot;+ objTState.getState());\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nI am in new State\r\nT1 : TERMINATED\r\n<\/pre>\n<p>A thread is in the <strong class=\"ctaHeader3\">BLOCKED<\/strong> state when it\u2019s currently not eligible to run. It enters this state when it is waiting for a monitor lock and is trying to access a section of code that is locked by some other thread.<br \/>\n<strong>BlockedState.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class BlockedState implements Runnable{\r\n    public void run(){\r\n      blockedResource();\r\n    }\r\n\r\n    public static synchronized void blockedResource(){\r\n        while(true){\r\n            \/\/Do Nothing\r\n        }\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) throws InterruptedException {\r\n        Thread objB1Thread = new Thread(new BlockedState());\r\n        Thread objB2Thread = new Thread(new BlockedState());\r\n\r\n        objB1Thread.start();\r\n        objB2Thread.start();\r\n\r\n        Thread.sleep(1000);\r\n\r\n        System.out.println(objB1Thread.getState());\r\n        System.out.println(objB2Thread.getState());\r\n        System.exit(0);\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nRUNNABLE\r\nBLOCKED\r\n<\/pre>\n<p>A thread is in <strong class=\"ctaHeader3\">WAITING<\/strong> state when it\u2019s waiting for some other thread to perform a particular action. According to JavaDocs, any thread can enter this state by calling any one of the following<br \/>\n<em>object.wait() (or) thread.join() (or) LockSupport.park()<\/em><\/p>\n<p><strong>WaitingState.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class WaitingState implements Runnable{\r\n    public void run(){\r\n        Thread objWaitState = new Thread(new SleepState());\r\n\r\n        objWaitState.start();\r\n\r\n        try {\r\n            objWaitState.join();\r\n        } catch (InterruptedException e) {\r\n            throw new RuntimeException(e);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><strong>SleepState.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class SleepState implements Runnable{\r\n    @Override\r\n    public void run() {\r\n        try {\r\n            Thread.sleep(5000);\r\n        } catch (InterruptedException e) {\r\n            throw new RuntimeException(e);\r\n        }\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) throws InterruptedException {\r\n       Thread objWaitingThread = new Thread(new WaitingState());\r\n       objWaitingThread.start();\r\n       objWaitingThread.sleep(1000);\r\n       System.out.println(&quot;T1 : &quot;+ objWaitingThread.getState());\r\n       System.out.println(&quot;Main : &quot;+Thread.currentThread().getState());\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nT1 : WAITING\r\nMain : RUNNABLE\r\n<\/pre>\n<p>A thread is in <strong class=\"ctaHeader3\">TIMED_WAITING<\/strong> state when it\u2019s waiting for another thread to perform a particular action within a stipulated amount of time. According to JavaDocs, there are five ways to put a thread on TIMED_WAITING state:<br \/>\n<em>thread.sleep(long millis) (or) wait(int timeout) (or) wait(int timeout, int nanos) thread.join(long millis) (or) LockSupport.parkNanos (or) LockSupport.parkUntil<\/em><\/p>\n<p><strong>TimedWaitState.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class TimedWaitState implements Runnable{\r\n    @Override\r\n    public void run() {\r\n        try {\r\n            Thread.sleep(5000);\r\n        } catch (InterruptedException e) {\r\n            throw new RuntimeException(e);\r\n        }\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) throws InterruptedException {\r\n        Thread objTWState = new Thread(new TimedWaitState());\r\n        objTWState.start();\r\n        Thread.sleep(2000);\r\n        System.out.println(&quot;T1 : &quot;+ objTWState.getState());\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nT1 : TIMED_WAITING\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>NEW \u2013 a newly created thread that has not yet started the execution RUNNABLE \u2013 either running or ready for execution but it\u2019s waiting for resource allocation BLOCKED \u2013 waiting to acquire a monitor lock to enter or re-enter a synchronized block\/method WAITING \u2013 waiting for some other thread to perform a particular action without&hellip; <a href=\"https:\/\/codethataint.com\/blog\/threads-and-states\/\">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":[349,271],"tags":[],"class_list":["post-5030","post","type-post","status-publish","format-standard","hentry","category-basics-threads","category-code-examples-threads"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/5030","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=5030"}],"version-history":[{"count":6,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/5030\/revisions"}],"predecessor-version":[{"id":5038,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/5030\/revisions\/5038"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=5030"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=5030"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=5030"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}