{"id":5879,"date":"2022-08-31T03:30:56","date_gmt":"2022-08-30T22:00:56","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/"},"modified":"2022-08-31T03:30:56","modified_gmt":"2022-08-30T22:00:56","slug":"solved-what-is-wrong-with-it","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/","title":{"rendered":"[Solved] What is wrong with it?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-27877194\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"27877194\" data-parentid=\"27876598\" data-score=\"0\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>The thread you create in <code>main<\/code> invokes <code>MyThread#k()<\/code> which goes into a wait. At that point, that thread will do nothing else until it is awakened or interrupted. But the only place in your code where it could possibly be awakened is the <code>notify<\/code> in <code>MyThread#m()<\/code>. Since nothing in your program calls that method, the thread can never be awoken.<\/p>\n<p>What you probably want is to add a call to <code>s.m()<\/code> right after <code>s.start()<\/code> in your main program. That way your main thread will execute the <code>notify<\/code> that&#8217;s needed to wake up your thread.<\/p>\n<p>Unfortunately, that&#8217;s very unlikely to work. The problem is that <code>s.start()<\/code> causes your created thread to become ready to run, but it doesn&#8217;t necessarily run immediately. It could well happen that your call to <code>s.m()<\/code> will complete before the created thread does anything. And then you&#8217;ll still have exactly the same result as before, except that you&#8217;ll see the integers 0..6 printed out before <code>before wait<\/code>. The <code>notify<\/code> will do nothing, because the child thread has not yet performed its <code>wait<\/code>. (And by the way, since both <code>MyThread#k()<\/code> and <code>MyThread#m()<\/code> are both synchronized, increasing your loop limit in <code>MyThread#m()<\/code> won&#8217;t change a thing&#8230; the child thread won&#8217;t be able to enter <code>MyThread#k()<\/code> while <code>MyThread#m()<\/code> is running. You could improve that by putting the <code>notify<\/code> in a sycnchronized block rather than making all of <code>MyThread#m()<\/code> synchronized.)<\/p>\n<p>You can try to get around this by adding <code>Thread.sleep(1000)<\/code> before <code>s.m()<\/code> in your main program. That will almost certainly work because your main thread will yield execution, giving your JVM the opportunity to schedule the child thread for some useful work. By the time the main thread wakes out of its sleep and performs its <code>s.m()<\/code> call, the child will probably have executed its <code>wait<\/code> and you will then see your <code>do something after wait<\/code> message.<\/p>\n<p>But that&#8217;s still pretty crummy, because it still depends on scheduling events that you don&#8217;t really have any control over. There&#8217;s still no <strong>guarantee<\/strong> that the <code>wait<\/code> will happen before the <code>notify<\/code>.<\/p>\n<p>This is why when using wait\/notify you should generally arrange for there to be some sort of reliable test as to whether whatever you&#8217;re waiting to be done has actually occurred. This should be a condition that, once it turns turns true, will remain true at least until the test has been subsequently performed. Then your typical wait loop looks something like this:<\/p>\n<pre><code>while (!isDone()) {\n    synchronized(monitorObject) {\n        try {\n            monitorObject.wait();\n        } catch (InterruptedException e) {\n        }\n    }\n}\n<\/code><\/pre>\n<p>Putting the whole thing in a loop takes care of premature waking, e.g. due to InterruptedException.<\/p>\n<p>If the required work has already occurred by the time this code is executed, no <code>wait<\/code> occurs, and the <code>notify<\/code> executed by the code that did the work was a no-op. Otherwise, this code waits, and the code completing the work will eventually do a <code>notify<\/code> which will wake this code up as required. Of course, it&#8217;s critical that, at the time the <code>notify<\/code> is performed, the wait condition (<code>isDone()<\/code> above) be true and remain true at least until tested.<\/p>\n<p>Here&#8217;s a corrected version of your code that incorporates a proper wait loop. If you comment out the <code>Thread.sleep()<\/code> call, you will likely not see the <code>waiting<\/code> message, because the work will complete before the wait loop even starts. With the sleep included, you&#8217;ll probably see the <code>waiting<\/code> message. But either way, the program will work properly.<\/p>\n<pre><code>public static void main(String[] argv) throws Exception {\n    MyThread s = new MyThread();\n    s.start();\n    Thread.sleep(1000);\n    s.m();\n}\n\nclass MyThread extends Thread {\n\n    @Override\n    public void run() {\n        k();\n    }\n\n    private boolean done = false;\n\n    public void k() {\n        System.out.println(\"before wait\");\n        while (!done) {\n            System.out.println(\"waiting\");\n            synchronized (this) {\n                try {\n                    wait();\n                } catch (InterruptedException e) {\n                }\n            }\n        }\n\n        System.out.println(\"do something after wait\");\n    }\n\n    public void m() {\n        for (int i = 0; i &lt; 6; i++) {\n            System.out.println(i);\n        }\n        synchronized (this) {\n            done = true;\n            notify();\n        }\n    }\n}\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved What is wrong with it? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] The thread you create in main invokes MyThread#k() which goes into a wait. At that point, that thread will do nothing else until it is awakened or interrupted. But the only place in your code where it could possibly be awakened is the notify in MyThread#m(). Since nothing in your program calls that method, &#8230; <a title=\"[Solved] What is wrong with it?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/\" aria-label=\"More on [Solved] What is wrong with it?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[323,884],"class_list":["post-5879","post","type-post","status-publish","format-standard","hentry","category-solved","tag-java","tag-multithreading"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>[Solved] What is wrong with it? - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] What is wrong with it? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] The thread you create in main invokes MyThread#k() which goes into a wait. At that point, that thread will do nothing else until it is awakened or interrupted. But the only place in your code where it could possibly be awakened is the notify in MyThread#m(). Since nothing in your program calls that method, ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-30T22:00:56+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] What is wrong with it?\",\"datePublished\":\"2022-08-30T22:00:56+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/\"},\"wordCount\":545,\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"keywords\":[\"java\",\"multithreading\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/\",\"name\":\"[Solved] What is wrong with it? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\"},\"datePublished\":\"2022-08-30T22:00:56+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/solved-what-is-wrong-with-it\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] What is wrong with it?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#website\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/jassweb.com\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/jass-website-logo-1.png\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/wp-content\\\/uploads\\\/2021\\\/02\\\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/#\\\/schema\\\/person\\\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777613206\",\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777613206\",\"contentUrl\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/wp-content\\\/litespeed\\\/avatar\\\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777613206\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\\\/\\\/jassweb.com\"],\"url\":\"https:\\\/\\\/jassweb.com\\\/solved\\\/author\\\/jaspritsinghghumangmail-com\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] What is wrong with it? - JassWeb","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:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] What is wrong with it? - JassWeb","og_description":"[ad_1] The thread you create in main invokes MyThread#k() which goes into a wait. At that point, that thread will do nothing else until it is awakened or interrupted. But the only place in your code where it could possibly be awakened is the notify in MyThread#m(). Since nothing in your program calls that method, ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/","og_site_name":"JassWeb","article_published_time":"2022-08-30T22:00:56+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] What is wrong with it?","datePublished":"2022-08-30T22:00:56+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/"},"wordCount":545,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["java","multithreading"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/","url":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/","name":"[Solved] What is wrong with it? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-30T22:00:56+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-wrong-with-it\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] What is wrong with it?"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777613206","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777613206","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1777613206","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/5879","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=5879"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/5879\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=5879"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=5879"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=5879"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}