{"id":89378,"date":"2024-03-28T18:00:51","date_gmt":"2024-03-28T12:30:51","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=89378"},"modified":"2024-03-28T18:00:51","modified_gmt":"2024-03-28T12:30:51","slug":"threadgroup-in-java","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/","title":{"rendered":"ThreadGroup in Java with Examples"},"content":{"rendered":"<p>A thread group represents a set of threads. In addition, a thread group may also contain other thread groups. Thread groups form a tree in which each thread group has a parent except for the initial thread group.<\/p>\n<h2>How ThreadGroup Works In Java?<\/h2>\n<p>A thread group is a collection of several related threads. A thread pool allows developers to process multiple Java threads simultaneously and is available in the java.lang package.Internally, a thread group can be thought of as a tree in which every thread has a parent, except for a parent thread that is not assigned to it.<\/p>\n<p>It should be noted that a thread belonging to one particular thread group is able to obtain information about the same thread group it belongs to, but has no information on its parent or any other thread group.<\/p>\n<p><strong>Example code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class Techvidvan Test implements Runnable{\npublic void run()\n{\n       }\n  public static void main(String[] args) {\n      ThreadGroupTest threadGroupTest = new ThreadGroupTest();\n      ThreadGroup threadGroup = new ThreadGroup(\"Parent Thread Group\");\n       Thread t1 = new Thread(threadGroup, threadGroupTest,\"T1\");\n      t1.start();\n      Thread t2 = new Thread(threadGroup, threadGroupTest,\"T2\");\n      t2.start();\n      Thread t3 = new Thread(threadGroup, threadGroupTest,\"T3\");\n      t3.start();\nSystem.out.println(\"Thread Group Name: \"+threadGroup.getName());\n      threadGroup.list();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>Creating Thread-<\/strong>1<br \/>\n<strong>Starting Thread-<\/strong>1<br \/>\n<strong>Creating Thread-<\/strong>2<br \/>\n<strong>Starting Thread-<\/strong>2<br \/>\n<strong>Running Thread-<\/strong>1<br \/>\n<strong>Thread: Thread-<\/strong>1, 4<br \/>\n<strong>Running Thread<\/strong>-2<\/p>\n<h3>Life Cycle Of Thread:<\/h3>\n<p>In Java, a thread always exists in any of the following states. <strong>These states are:<\/strong><\/p>\n<p>New<br \/>\nActive<br \/>\nBlocked \/ Waiting<br \/>\nTimed waiting<br \/>\nEnded<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.lang.*;\nclass NewThread extends Thread\n{\n    NewThread(String threadname, ThreadGroup tgob)\n    {\n        super(tgob, threadname);\n        start();\n    }\npublic void run()\n    {\n\n        for (int i = 0; i &lt; 1000; i++)\n        {\n            try\n            {\n                Thread.sleep(10);\n            }\n            catch (InterruptedException ex)\n            {\n                System.out.println(\"Exception encounterted\");\n            }\n        }\n        System.out.println(Thread.currentThread().getName() +\n            \" finished executing\");\n    }\n}\npublic class ThreadGroupDemo\n{\n    public static void main(String arg[]) throws InterruptedException\n    {\n        \/\/ creating the thread group\n        ThreadGroup gfg = new ThreadGroup(\"gfg\");\n\n        ThreadGroup gfg_child = new ThreadGroup(gfg, \"child\");\n\n        NewThread t1 = new NewThread(\"one\", gfg);\n        System.out.println(\"Starting one\");\n        NewThread t2 = new NewThread(\"two\", gfg);\n        System.out.println(\"Starting two\");\n\n        \/\/ checking the number of active thread\n        System.out.println(\"number of active thread group: \"\n                        + gfg.activeGroupCount());\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>The state of thread t1 after spawning it &#8211;<\/strong> NEW<br \/>\n<strong>The state of thread t1 after invoking the method start() on it &#8211;<\/strong> RUNNABLE<br \/>\n<strong>The state of thread t2 after spawning it &#8211;<\/strong> NEW<br \/>\n<strong>the state of thread t2 after calling the method start() on it &#8211;<\/strong> RUNNABLE<br \/>\n<strong>The state of thread t1 while it invoked the method join() on thread t2 &#8211;<\/strong>TIMED_WAITING<br \/>\n<strong>The state of thread t2 after invoking the method sleep() on it &#8211;<\/strong> TIMED_WAITING<br \/>\n<strong>The state of thread t2 when it has completed its execution &#8211;<\/strong> TERMINATED<\/p>\n<p>void destroy() Destroys a thread groupint enumerate(Thread[] list) Copies each thread in the thread group to the specified array int enumerate(ThreadGroup[] list) Copies each active subgroup in the thread group to the specified array int enumerate.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.lang.*;\nclass NewThread extends Thread\n{\n    NewThread(String threadname, ThreadGroup tgob)\n    {\n        super(tgob, threadname);\n        start();\n    }\npublic void run()\n    {\n\n        for (int i = 0; i &lt; 10; i++)\n        {\n            try\n            {\n                Thread.sleep(10);\n            }\n            catch (InterruptedException ex)\n            {\n                System.out.println(\"Exception encounterted\");\n            }\n        }\n    }\n}\npublic class ThreadGroupDemo\n{\n    public static void main(String arg[]) throws InterruptedException,\n        SecurityException\n    {\n        ThreadGroup gfg = new ThreadGroup(\"Parent thread\");\n\n        ThreadGroup gfg_child = new ThreadGroup(gfg, \"child thread\");\n\n        NewThread t1 = new NewThread(\"one\", gfg);\n        System.out.println(\"Starting one\");\n        NewThread t2 = new NewThread(\"two\", gfg);\n        System.out.println(\"Starting two\");\n        t1.join();\n        t2.join();\n        gfg_child.destroy();\n        System.out.println(gfg_child.getName() + \" destroyed\");\n        gfg.destroy();\n        System.out.println(gfg.getName() + \" destroyed\");\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nStarting the first<br \/>\nStarting the second<br \/>\nthe first thread has finished executing<br \/>\nthe second thread has finished executing<br \/>\nthe child group is destroyed.<br \/>\nthe parent group is destroyed.<\/p>\n<p>If recursion is true, calls this operation recursively int enumerate(threadgroup list[], boolean recursion) Copies each active subgroup in the thread group to the specified array.<\/p>\n<p>If recursion is true, calls this operation recursively int getMaximumPriority() Returns the maximum priority of the thread group getName() Returns the name of the thread group groupThreadGroup getParent() Returns the parent of the thread group.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import java.lang.*;\nclass NewThread extends Thread\n{\n    NewThread(String threadname, ThreadGroup tgob)\n    {\n        super(tgob, threadname);\n        start();\n    }\npublic void run()\n    {\n\n        for (int i = 0; i &lt; 10; i++)\n        {\n            try\n            {\n                Thread.sleep(10);\n            }\n            catch (InterruptedException ex)\n            {\n            System.out.println(\"Thread \" + Thread.currentThread().getName()\n                                + \" interrupted\");\n            }\n        }\n        System.out.println(Thread.currentThread().getName() +\n            \" finished executing\");\n    }\n}\npublic class ThreadGroupDemo\n{\n    public static void main(String arg[]) throws InterruptedException,\n        SecurityException\n    {\n        ThreadGroup gfg = new ThreadGroup(\"Parent thread\");\n        ThreadGroup gfg_child = new ThreadGroup(gfg, \"child thread\");\n\n        NewThread t1 = new NewThread(\"one\", gfg);\n        System.out.println(\"Starting \" + t1.getName());\n        NewThread t2 = new NewThread(\"two\", gfg);\n        System.out.println(\"Starting \" + t2.getName());\n        gfg.interrupt();\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nStarting hello thread&#8230;<br \/>\nStarting goodbye thread&#8230;<br \/>\nHello<br \/>\nHello<br \/>\nHello<br \/>\nHello<br \/>\nHello<br \/>\nHello<br \/>\nGoodbye<br \/>\nGoodbye<br \/>\nGoodbye<br \/>\nGoodbye<br \/>\nGoodbye<br \/>\n&#8230;&#8230;.<\/p>\n<h3>Need For Java Thread Group:<\/h3>\n<p>Java thread pooling allows developers to process multiple Java threads simultaneously, which is available in Java. lang package. In theory, a thread group is a tree in which every thread has a parent, except for a parent thread that is not assigned to it. All Java threads are members of the thread pool. Thread groups are a mechanism for accumulating multiple threads in an object and manipulating them at once, instead of individually.<\/p>\n<h4>Advantages:<\/h4>\n<ul>\n<li>Logical organization of your threads (for diagnostic purposes).<\/li>\n<li>You can break() all threads in a group. (Abort is perfectly fine, unlike suspend(), continue() and stop()).<\/li>\n<li>You can set the maximum priority of threads in a group. (not sure how widely useful this is, but there you have it).<\/li>\n<li>Sets the ThreadGroup as a daemon. (So \u200b\u200bany new threads added to it will be daemon threads).<\/li>\n<li>It allows you to override its uncaughtExceptionHandler so that if one of the threads in the group throws an exception, you&#8217;ll have a callback to handle it.<\/li>\n<\/ul>\n<h4>Disadvantages:<\/h4>\n<p><strong> Complicatity:<\/strong> It&#8217;s a matter of thinking about how different threads are going to interact and coordinate with one another, which is what adds complexity to your code. If this is the case, it may be hard to decipher and debug your code<\/p>\n<p><strong>Resource overhead:<\/strong> System resources, e.g. memory or processing power, are needed to create and manage threads. This, in particular when you build a lot of threads, can have an effect on your program&#8217;s performance.<\/p>\n<p><strong>Race condition:<\/strong> when multiple threads attempt to access and modify a common set of data at the same time, race conditions can occur if it is not clear what their final state will be. To debug this could be hard to do, and it may result in unpredictable behavior within your program. A deadlock occurs when, in order to release the resource, two or more threads wait on one another and are prevented from leaving an infinite loop.<\/p>\n<p><strong>Scheduling:<\/strong> You don&#8217;t guarantee the order of threads that are scheduled, which can cause unexpected behavior in your program.<\/p>\n<h3>Conclusion<\/h3>\n<p>A set of threads is represented by a group of threads. A second group of fibers may also be included in the fiber group. A thread group forms a tree in which each thread group has a parent group except the initial thread group.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A thread group represents a set of threads. In addition, a thread group may also contain other thread groups. Thread groups form a tree in which each thread group has a parent except for&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":89443,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[5422,5423,5424,5425,5426],"class_list":["post-89378","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-thread-group","tag-java-thread-group-with-examples","tag-thread-group","tag-thread-group-in-java","tag-thread-group-in-java-with-examples"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>ThreadGroup in Java with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java thread group can be thought of as a tree in which every thread has a parent, except for a parent thread that is not assigned to it.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"ThreadGroup in Java with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java thread group can be thought of as a tree in which every thread has a parent, except for a parent thread that is not assigned to it.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-03-28T12:30:51+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"ThreadGroup in Java with Examples - TechVidvan","description":"Java thread group can be thought of as a tree in which every thread has a parent, except for a parent thread that is not assigned to it.","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:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/","og_locale":"en_US","og_type":"article","og_title":"ThreadGroup in Java with Examples - TechVidvan","og_description":"Java thread group can be thought of as a tree in which every thread has a parent, except for a parent thread that is not assigned to it.","og_url":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2024-03-28T12:30:51+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"ThreadGroup in Java with Examples","datePublished":"2024-03-28T12:30:51+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/"},"wordCount":821,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#primaryimage"},"thumbnailUrl":"","keywords":["java thread group","java thread group with examples","thread group","thread group in java","thread group in java with examples"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/","url":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/","name":"ThreadGroup in Java with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#primaryimage"},"thumbnailUrl":"","datePublished":"2024-03-28T12:30:51+00:00","description":"Java thread group can be thought of as a tree in which every thread has a parent, except for a parent thread that is not assigned to it.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/threadgroup-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"ThreadGroup in Java with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89378","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=89378"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89378\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=89378"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=89378"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=89378"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}