{"id":85,"date":"2016-01-13T22:45:43","date_gmt":"2016-01-13T22:45:43","guid":{"rendered":"http:\/\/kaizen-koka.com\/?p=85"},"modified":"2016-01-14T05:42:26","modified_gmt":"2016-01-14T05:42:27","slug":"multithreading","status":"publish","type":"post","link":"https:\/\/kaizen-koka.com\/?p=85","title":{"rendered":"MultiThreading"},"content":{"rendered":"<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\">\n<tbody>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t<b>S.No.<\/b>\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\t<b>Process based Multitasking programming<\/b>\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\t<b>Thread based Multitasking programming<\/b>\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t1\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tA process is essence of program that is executing which running parallel\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tThread is a such part of multithreaded program which defines separate path for execution\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t2\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tIt allows you to run java compiler and text editor at a same time.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tIt doesn&rsquo;t support java compilerand text editor run simultaneously.Both have performed different tasks\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t3\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tIn process based multitasking a process or a program is the smallest unit.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tIn thread based multitasking a thread is the smallest unit.\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t4\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tIn process based multitasking a process or a program is the smallest unit.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tIn thread based multitasking a thread is the smallest unit.\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t5\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tProgram is a bigger unit.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tThread is a smaller unit.\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t6\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tProcess based multitasking requires more overhead.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tThread based multitasking requires less overhead.\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t7\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tContext switching difficult and slow\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tContext switching is easy and fast\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t8\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tProcess requires its own address space.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tThreads share same address space.\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t9\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tHere, it is unable to gain access over idle time of CPU.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tIt allows taking gain access over idle time taken by CPU\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t10\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tIt is not under control of java.\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tIt is totally under control of java.\n\t\t\t<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"49\">\n\t\t\t\t11\n\t\t\t<\/td>\n<td valign=\"top\" width=\"192\">\n\t\t\t\tProcess to Process communication is expensive\n\t\t\t<\/td>\n<td valign=\"top\" width=\"186\">\n\t\t\t\tThread to Thread communication is not expensive.\n\t\t\t<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>\n\t<span style=\"font-size:16px;\"><strong>Thread&nbsp;Life Cycle<\/strong><\/span>\n<\/p>\n<p>\n\t<a href=\"https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" data-attachment-id=\"90\" data-permalink=\"https:\/\/kaizen-koka.com\/?attachment_id=90\" data-orig-file=\"https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png?fit=666%2C507&amp;ssl=1\" data-orig-size=\"666,507\" data-comments-opened=\"0\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"thread_states\" data-image-description=\"\" data-image-caption=\"\" data-medium-file=\"https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png?fit=300%2C228&amp;ssl=1\" data-large-file=\"https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png?fit=666%2C507&amp;ssl=1\" alt=\"thread_states\" class=\"aligncenter size-full wp-image-90\" height=\"507\" src=\"https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png?resize=666%2C507\" width=\"666\" srcset=\"https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png?w=666&amp;ssl=1 666w, https:\/\/i0.wp.com\/kaizen-koka.com\/wp-content\/uploads\/2016\/01\/thread_states.png?resize=300%2C228&amp;ssl=1 300w\" sizes=\"auto, (max-width: 666px) 100vw, 666px\" \/><\/a>\n<\/p>\n<p>\n\tisAlive() : Method is used to check whether the thread is alive or dead.\n<\/p>\n<p>\n\tYield(): When you called yield() method on the running thread. Running thread will give a chance to another thread which is in ready to run state. i.e, Running thread will be placed back to ready to run state. Some other thread which has the highest priority will be moved from ready-to-run state to running state but JVM doesn&rsquo;t guarantee.\n<\/p>\n<p>\n\tJoin(): When you call join method on the threads then the join thread will be completed first and then parent thread from where the other threads are started. Example, from main method 2 child threads t1 and t2 are started. When I call join method on t1 and t2 then main thread wait until child thread finishes it task.\n<\/p>\n<p>\n\t<strong>Daemon Threads<\/strong>: Are the service threads. Daemon threads live as long as dependent threads are running. You can make any thread as deamon by using the following methods.\n<\/p>\n<p>\n\tVoid setDaemon(boolean);\n<\/p>\n<p>\n\tBoolean isDaemon();&nbsp;&nbsp; We can check whether the thread is daemon thread or not.\n<\/p>\n<p>\n\tThreads can created in 2 ways :\n<\/p>\n<ol>\n<li>\n\t\tBy extending thread class\n\t<\/li>\n<li>\n\t\tBy implementing runnable interface.\n\t<\/li>\n<\/ol>\n<p>\n\tImplementing through runnable interface is best option. When you extend the thread class, we don&rsquo;t have a chance to extend any other class, bcoz no multiple inheritance with java classes, where as when you implement runnable interface we can extend some other class also. And when you extend thread classes all the implemented methods in the thread class will be loaded in to the memory. Where are when you implement runnable interface we don&rsquo;t get such problem.\n<\/p>\n<p>\n\t&nbsp;&nbsp; Scheduling Algorithm:&nbsp;\n<\/p>\n<ol>\n<li>\n\t\t<strong>Primitive Scheduling Alg :<\/strong>&nbsp;&nbsp; Suppose 2 threads t1 and t2 enter into ready to run state with the priorities 4 and 6 respectively. Now T2 gets the CPU time, because of it has highest than T1. Now T2 is running and t1 is in ready to run state. Another thread called t3 with priority 9 and entered in to ready to run state. And t3 has highest priority than the running thread. And then t2 will be preempted and t3 enter into running state.\n\t<\/li>\n<li>\n\t\t<strong>Time slice or Round Robin Alg<\/strong> : In this alg, each thread will be given fixed amount of time and CPU time will be allocated for each thread based on FCFS(First come First Serve) or Primitive Algorithm and thread will be running state for specified quantum time. After the time is over thread will be back to ready to run state and another thread will be entered in to running state and so on&hellip;\n\t<\/li>\n<\/ol>\n<p>\n\t&nbsp;\n<\/p>\n<p>\n\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>&nbsp;Dead Locks :<\/strong>\n<\/p>\n<p>\n\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Example : Thread t1 which is holding resource r1 is waiting for resource r2 and thread t2 which is holding a resource R2 and waiting for resource R1. T1 releases the resource R1 after serving R2 and T2 releases Resource R2 after serving R1. They won&rsquo;t release the resource and they won&rsquo;t get the resource also. Simply T1 and t2 will be blocked. No chance to move from out of block state. This situation is called dead lock.\n<\/p>\n<p>\n\t&nbsp;\n<\/p>\n<p>\n\tThread Priorities: We can give an integer number ranging from 1 -10 as priority to the threads.&nbsp; They are 3 constraints defined inside the thread class.\n<\/p>\n<ol>\n<li>\n\t\tMIN_PRIORITY&nbsp;&nbsp;&nbsp; &#8211; 1\n\t<\/li>\n<li>\n\t\tNORM_PRIORITY -5\n\t<\/li>\n<li>\n\t\tMAX_PRIORITY &#8211; 10\n\t<\/li>\n<\/ol>\n<p>\n\t&nbsp;&nbsp;&nbsp; We have two methods to find the priority of the thread and to change the priority of the thead.\n<\/p>\n<p>\n\t1)int getPriority()\n<\/p>\n<p>\n\t2)void serPriorities(int)\n<\/p>\n<p>\n\t&nbsp;\n<\/p>\n<p>\n\t&nbsp;<strong>Synchronization<\/strong>: In multi-threading environment when all threads are accessing the object concurrently. Some time we can get inconsistent results. To avoid inconsistent results, I don&rsquo;t want to allow all the threads to access the object concurrently. I want to allow one-by-one to access the object. This is known as Synchronization.\n<\/p>\n<p>\n\t&nbsp;&nbsp;&nbsp;&nbsp; When you synchronize the object, object will be locked and will be monitored. Threads which would like to use locked objects will enter in to the monitor and uses the locked object. After using the object, come out of the monitor. The threads outside the monitor unable to access the locked objects. We can do the synchronization using the modifier called as synchronize modifier. We can use this modifier in 2 ways,\n<\/p>\n<ol>\n<li>\n\t\tMethod level synchronization\n\t<\/li>\n<li>\n\t\tBlock level synchronization\n\t<\/li>\n<\/ol>\n<p>\n\t&nbsp;\n<\/p>\n<ol>\n<li>\n\t\tSynchronized modifier is not allowed for classes, interfaces and variables.\n\t<\/li>\n<li>\n\t\tWhen you call any synchronized method with an object &ndash; that object will be locked. Then no other threads use that object.\n\t<\/li>\n<li>\n\t\tWhen you are using block level synchronization, you should pass any object to the block. And that passed object will be synchronized or locked.\n\t<\/li>\n<li>\n\t\t&nbsp;In method level synchronization &ndash; Object of the class which contains synchronized method will be locked. Where as in block level synchronization, the objects which we are passing to synchronized block (any object ) will be locked.\n\t<\/li>\n<li>\n\t\t&nbsp;<strong>In case of synchronized method, lock is acquired by thread on object when it enter method and released when it leaves method. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.<\/strong>\n\t<\/li>\n<\/ol>\n<p>\n\t<br \/>\n\t<strong><span style=\"font-size:16px;\">Programs :<\/span><\/strong>\n<\/p>\n<pre class=\"brush:java;\">\r\npublic class SystemThread {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tint x = 0;\r\n\t\tThread t1 = new Thread();\r\n\t\tt1.setName(&quot;Java&quot;);\r\n\r\n\t\tThread t2 = new Thread();\r\n\t\tt2.setName(&quot;Sql&quot;);\r\n\r\n\t\tfor (int i = 0; i &lt;= 10; i++) {\r\n\r\n\t\t\tSystem.out.println(t1.getName() + x);\r\n\t\t\ttry {\r\n\t\t\t\tt1.sleep(5000);\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\tSystem.out.println(t2.getName() + x);\r\n\t\t\tx++;\r\n\t\t}\r\n\t}\r\n}<\/pre>\n<p>\n\t<strong><span style=\"font-size:16px;\">By extending Thread<\/span><\/strong>\n<\/p>\n<pre class=\"brush:java;\">\r\npublic class ThreadExamp1 {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tnew MyThread1(&quot;java&quot;);\r\n\t\tnew MyThread1(&quot;Sql&quot;);\r\n\t}\r\n}\r\n\r\nclass MyThread1 extends Thread{\r\n\tstatic int a=1;\r\n\tString name;\r\n\t\r\n\tMyThread1(String name){\r\n\t\tsetName(name);\r\n\t\tstart();\r\n\t}\r\n\t\r\n\tpublic void run(){\r\n\t\tfor(int i=0;i&lt;10;i++){\r\n\t\t\ta++;\r\n\t\t\tSystem.out.println(getName()+&quot; &quot;+a);\r\n\t\t\ttry {\r\n\t\t\t\tThread.sleep(5000);\r\n\t\t\t\t\/\/wait(5000);\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n}<\/pre>\n<p>\n\t<span style=\"font-size:16px;\"><strong>By implementing Runnable<\/strong><\/span>\n<\/p>\n<pre class=\"brush:java;\">\r\npublic class RunnableExample {\r\n\tpublic static void main(String[] args) {\r\n        new MyRunnable(&quot;java&quot;);\r\n        new MyRunnable(&quot;sql&quot;); \r\n\t}\r\n}\r\nclass MyRunnable implements Runnable{\r\n\tint a=0;\r\n\tThread t;\r\n\t\r\n\tMyRunnable(String name){\r\n\t\tt = new Thread(this,name);\r\n\t\tt.start();\t\t\r\n\t}\r\n\tpublic void run() {\r\n\t  for(int i=0;i&lt;10;i++){\r\n\t\t  System.out.println(t.getName()+&quot; &quot;+i+&quot; &quot;+a);\r\n\t\t  try {\r\n\t\t\tt.sleep(1000);\r\n\t\t} catch (InterruptedException e) {\r\n\t\t\t\/\/ TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\t  a++;\r\n\t  }\r\n  }\t\r\n}<\/pre>\n<p>\n\t<span style=\"font-size:16px;\"><strong>Synchronization Example<\/strong><\/span>\n<\/p>\n<pre class=\"brush:java;\">\r\npublic class SynchronizationExample {\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tIncrementOper inc1 = new IncrementOper();\r\n\t\t\r\n\t\tSyncScenario thread1 = new SyncScenario(&quot;java&quot;, inc1);\r\n\t\tSyncScenario thread2 = new SyncScenario(&quot;sql&quot;, inc1);\r\n\t}\r\n}\r\nclass SyncScenario implements Runnable{\r\n\tString name;\r\n\tIncrementOper inc;\r\n\tThread t;\r\n\tSyncScenario(String name, IncrementOper inc){\r\n\t\tthis.name=name;\r\n\t\tthis.inc=inc;\r\n\t\tt =new Thread(this,name);\r\n\t\tt.start();\r\n\t}\r\n\tpublic void run() {\r\n\t\tSystem.out.println(&quot;Thread started: &quot;+t.getName());\r\n\t\tsynchronized(inc){\r\n\t\t\tinc.noSynMethod(name);\r\n\t\t}\r\n\t\tSystem.out.println(&quot;Thread ended: &quot;+t.getName());\r\n\t}\r\n}\r\nclass IncrementOper {\r\n\t\r\n\tpublic synchronized void incMethod(String name){\r\n\t\tfor(int i=0;i&lt;5;i++){\r\n\t\t\tSystem.out.println(&quot;Running Thread name:&quot;+name+&quot; count&quot;+i);\r\n\t\t}\r\n  }\r\n\tpublic void noSynMethod(String name){\r\n\t\tfor(int i=0;i&lt;5;i++){\r\n\t\t\tincMethod(name);\r\n\t\t\tSystem.out.println(&quot;Running No Sync:&quot;+name+&quot; count&quot;+i);\r\n\t\t}\r\n\t}\t\r\n}<\/pre>\n<p>\n\t&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>S.No. Process based Multitasking programming Thread based Multitasking programming 1 A process is essence of program that is executing which running parallel Thread is a such part of multithreaded program [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[3,2],"tags":[],"class_list":["post-85","post","type-post","status-publish","format-standard","hentry","category-java","category-technology"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p70lnf-1n","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=\/wp\/v2\/posts\/85","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=85"}],"version-history":[{"count":5,"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=\/wp\/v2\/posts\/85\/revisions"}],"predecessor-version":[{"id":91,"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=\/wp\/v2\/posts\/85\/revisions\/91"}],"wp:attachment":[{"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=85"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=85"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kaizen-koka.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=85"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}