{"id":3449,"date":"2019-06-20T11:43:59","date_gmt":"2019-06-20T11:43:59","guid":{"rendered":"http:\/\/softlect.in\/?p=3449"},"modified":"2019-06-20T12:02:46","modified_gmt":"2019-06-20T12:02:46","slug":"java-multithreading","status":"publish","type":"post","link":"http:\/\/softlect.com\/index.php\/java-multithreading\/","title":{"rendered":"Java Multithreading"},"content":{"rendered":"<h1><a name=\"_Toc179309645\"><\/a><strong>Multithreaded Programming<\/strong><\/h1>\n<p>&nbsp;<\/p>\n<p>Java provides built-in support for <em>multithreaded programming. <\/em>A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a <em>thread, <\/em>and each thread defines a separate path of execution. A <em>process <\/em>is, in essence, a program that is executing. In a <em>thread-based <\/em>multitasking environment, the thread is the smallest unit of code. This means that a single program can perform two or more tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates, because idle time is common.<\/p>\n<h2><a name=\"_Toc179309646\"><\/a>The Java Thread Model<\/h2>\n<p>The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles. The value of a multithreaded environment is best understood in contrast to its counterpart. One thread can pause without stopping other parts of your program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized. Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run. Threads exist in several states. A thread can be <em>running. <\/em>It can be <em>ready to run <\/em>as soon as it gets CPU time. A running thread can be <em>suspended, <\/em>which temporarily suspends its activity. A suspended thread can then be <em>resumed, <\/em>allowing it to pick up where it left off. A thread can be <em>blocked <\/em>when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.<\/p>\n<h3><a name=\"_Toc179309647\"><\/a>The Thread Class and the Runnable Interface<\/h3>\n<p>Java\u2019s multithreading system is built upon the <strong>Thread <\/strong>class, its methods, and its interface, <strong>Runnable<\/strong>. <strong>Thread <\/strong>encapsulates a thread of execution. To create a new thread, your program will either extend <strong>Thread <\/strong>or implement the <strong>Runnable <\/strong>interface. The <strong>Thread <\/strong>class defines several methods that help manage threads. The ones that will be used in this chapter are shown here:<\/p>\n<p>&nbsp;<\/p>\n<h3><a name=\"_Toc179309648\"><\/a>The Main Thread<\/h3>\n<p>When a Java program starts up, one thread begins running immediately. This is usually called the <em>main thread <\/em>of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:<\/p>\n<ul>\n<li>It is the thread from which other \u201cchild\u201d threads will be spawned.<\/li>\n<li>Often it must be the last thread to finish execution because it performs various shutdown actions.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>Although the main thread is created automatically when your program is started, it can be controlled through a <strong>Thread <\/strong>object. To do so, you must obtain a reference to it by calling the method <strong>currentThread( )<\/strong>, which is a <strong>public static <\/strong>member of <strong>Thread<\/strong>. Its general form is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>static Thread currentThread( )<\/p>\n<p>&nbsp;<\/p>\n<p>This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread. Let\u2019s begin by reviewing the following example:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Controlling the main Thread.<\/p>\n<p>class CurrentThreadDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>Thread t = Thread.currentThread();<\/p>\n<p>System.out.println(&#8220;Current thread: &#8221; + t);<\/p>\n<p>\/\/ change the name of the thread<\/p>\n<p>t.setName(&#8220;My Thread&#8221;);<\/p>\n<p>System.out.println(&#8220;After name change: &#8221; + t);<\/p>\n<p>try {<\/p>\n<p>for(int n = 5; n &gt; 0; n&#8211;) {<\/p>\n<p>System.out.println(n);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread interrupted&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>In this program, a reference to the current thread (the main thread, in this case) is obtained by calling <strong>currentThread( )<\/strong>, and this reference is stored in the local variable <strong>t<\/strong>. Next, the program displays information about the thread. The program then calls <strong>setName( ) <\/strong>to change the internal name of the thread. Information about the thread is then redisplayed. Next, a loop counts down from five, pausing one second between<\/p>\n<p>each line. The pause is accomplished by the <strong>sleep( ) <\/strong>method. The argument to <strong>sleep( ) <\/strong>specifies the delay period in milliseconds. Notice the <strong>try<\/strong>\/<strong>catch <\/strong>block around this loop. The <strong>sleep( ) <\/strong>method in <strong>Thread <\/strong>might throw an <strong>InterruptedException<\/strong>. This would happen if some other thread wanted to interrupt this sleeping one. This example just prints a message if it gets interrupted. In a real program, you would need to handle this differently. Here is the output generated by this program:<\/p>\n<p>&nbsp;<\/p>\n<p>Current thread: Thread[main,5,main]<\/p>\n<p>After name change: Thread[My Thread,5,main]<\/p>\n<p>5<\/p>\n<p>4<\/p>\n<p>3<\/p>\n<p>2<\/p>\n<p>1<\/p>\n<p>&nbsp;<\/p>\n<p>Notice the output produced when <strong>t <\/strong>is used as an argument to <strong>println( )<\/strong>. This displays, in order: the name of the thread, its priority, and the name of its group. By default, the name of the main thread is <strong>main<\/strong>. Its priority is 5, which is the default value, and <strong>main <\/strong>is also the name of the group of threads to which this thread belongs. A <em>thread group <\/em>is a data structure that controls the state of a collection of threads as a whole. This process is managed by the particular run-time environment and is not discussed in detail here. After the name of the thread is changed, <strong>t <\/strong>is again output. This time, the new name of the thread is displayed. The <strong>sleep( ) <\/strong>method causes the thread from which it is called to suspend execution for the specified period of milliseconds. Its general form is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>static void sleep(long <em>milliseconds<\/em>) throws InterruptedException<\/p>\n<p>&nbsp;<\/p>\n<p>The number of milliseconds to suspend is specified in <em>milliseconds. <\/em>This method may throw an <strong>InterruptedException<\/strong>. As the preceding program shows, you can set the name of a thread by using <strong>setName( )<\/strong>. You can obtain the name of a thread by calling <strong>getName( ).<\/strong> These methods are members of the <strong>Thread <\/strong>class and are declared like this:<\/p>\n<p>&nbsp;<\/p>\n<p>final void setName(String <em>threadName<\/em>)<\/p>\n<p>final String getName( )<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>threadName <\/em>specifies the name of the thread.<\/p>\n<h2><a name=\"_Toc179309649\"><\/a>Creating a Thread<\/h2>\n<p>In the most general sense, you create a thread by instantiating an object of type <strong>Thread<\/strong>. Java defines two ways in which this can be accomplished:<\/p>\n<ul>\n<li>You can implement the <strong>Runnable <\/strong><\/li>\n<li>You can extend the <strong>Thread <\/strong>class, itself.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>Implementing Runnable<\/p>\n<p>The easiest way to create a thread is to create a class that implements the <strong>Runnable <\/strong>interface. <strong>Runnable <\/strong>abstracts a unit of executable code. You can construct a thread on any object that implements <strong>Runnable<\/strong>. To implement <strong>Runnable<\/strong>, a class need only implement a single method called <strong>run( )<\/strong>, which is declared like this:<\/p>\n<p>&nbsp;<\/p>\n<p>public void run( )<\/p>\n<p>&nbsp;<\/p>\n<p>Inside <strong>run( )<\/strong>, you will define the code that constitutes the new thread. It is important to understand that <strong>run( ) <\/strong>can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that <strong>run( ) <\/strong>establishes the entry point for another, concurrent thread of execution within your program. This thread will end when <strong>run( ) <\/strong>returns. After you create a class that implements <strong>Runnable<\/strong>, you will instantiate an object of type <strong>Thread <\/strong>from within that class. <strong>Thread <\/strong>defines several constructors. The one that we will use is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>Thread(Runnable <em>threadOb<\/em>, String <em>threadName<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>In this constructor, <em>threadOb <\/em>is an instance of a class that implements the <strong>Runnable <\/strong>interface. This defines where execution of the thread will begin. The name of the new thread is specified by <em>threadName<\/em>. After the new thread is created, it will not start running until you call its <strong>start( ) <\/strong>method, which is declared within <strong>Thread<\/strong>. In essence, <strong>start( ) <\/strong>executes a call to <strong>run( )<\/strong>. The <strong>start( ) <\/strong>method is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>void start( )<\/p>\n<p>&nbsp;<\/p>\n<p>Here is an example that creates a new thread and starts it running:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Create a second thread.<\/p>\n<p>class NewThread implements Runnable {<\/p>\n<p>Thread t;<\/p>\n<p>NewThread() {<\/p>\n<p>\/\/ Create a new, second thread<\/p>\n<p>t = new Thread(this, &#8220;Demo Thread&#8221;);<\/p>\n<p>System.out.println(&#8220;Child thread: &#8221; + t);<\/p>\n<p>t.start(); \/\/ Start the thread<\/p>\n<p>}<\/p>\n<p>\/\/ This is the entry point for the second thread.<\/p>\n<p>public void run() {<\/p>\n<p>try {<\/p>\n<p>for(int i = 5; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(&#8220;Child Thread: &#8221; + i);<\/p>\n<p>Thread.sleep(500);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Child interrupted.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Exiting child thread.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class ThreadDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>new NewThread(); \/\/ create a new thread<\/p>\n<p>try {<\/p>\n<p>for(int i = 5; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(&#8220;Main Thread: &#8221; + i);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread interrupted.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Main thread exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>Inside <strong>NewThread<\/strong>\u2019s constructor, a new <strong>Thread <\/strong>object is created by the following statement:<\/p>\n<p>&nbsp;<\/p>\n<p>t = new Thread(this, &#8220;Demo Thread&#8221;);<\/p>\n<p>&nbsp;<\/p>\n<p>Passing <strong>this <\/strong>as the first argument indicates that you want the new thread to call the <strong>run( ) <\/strong>method on <strong>this <\/strong>object. Next, <strong>start( ) <\/strong>is called, which starts the thread of execution beginning at the <strong>run( ) <\/strong>method. This causes the child thread\u2019s <strong>for <\/strong>loop to begin. After calling <strong>start( )<\/strong>, <strong>NewThread<\/strong>\u2019s constructor returns to <strong>main( )<\/strong>. When the main thread resumes, it enters its <strong>for <\/strong>loop. Both threads continue running, sharing the CPU, until their loops finish. The output produced by this program is as follows:<\/p>\n<p>Child thread: Thread[Demo Thread,5,main]<\/p>\n<p>Main Thread: 5<\/p>\n<p>Child Thread: 5<\/p>\n<p>Child Thread: 4<\/p>\n<p>Main Thread: 4<\/p>\n<p>Child Thread: 3<\/p>\n<p>Child Thread: 2<\/p>\n<p>Main Thread: 3<\/p>\n<p>Child Thread: 1<\/p>\n<p>Exiting child thread.<\/p>\n<p>Main Thread: 2<\/p>\n<p>Main Thread: 1<\/p>\n<p>Main thread exiting.<\/p>\n<p>&nbsp;<\/p>\n<p>As mentioned earlier, in a multithreaded program, often the main thread must be the last thread to finish running.\u00a0 The program ensures that the main thread finishes last, because the main thread sleeps for 1,000 milliseconds between iterations, but the child thread sleeps for only 500 milliseconds. This causes the child thread to terminate earlier than the main thread.<\/p>\n<p>&nbsp;<\/p>\n<h2><a name=\"_Toc179309650\"><\/a>Extending Thread<\/h2>\n<p>The second way to create a thread is to create a new class that extends <strong>Thread<\/strong>, and then to create an instance of that class. The extending class must override the <strong>run( ) <\/strong>method, which is the entry point for the new thread. It must also call <strong>start( ) <\/strong>to begin execution of the new thread. Here is the preceding program rewritten to extend <strong>Thread<\/strong>:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Create a second thread by extending Thread<\/p>\n<p>class NewThread extends Thread {<\/p>\n<p>NewThread() {<\/p>\n<p>\/\/ Create a new, second thread<\/p>\n<p>super(&#8220;Demo Thread&#8221;);<\/p>\n<p>System.out.println(&#8220;Child thread: &#8221; + this);<\/p>\n<p>start(); \/\/ Start the thread<\/p>\n<p>}<\/p>\n<p>\/\/ This is the entry point for the second thread.<\/p>\n<p>public void run() {<\/p>\n<p>try {<\/p>\n<p>for(int i = 5; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(&#8220;Child Thread: &#8221; + i);<\/p>\n<p>Thread.sleep(500);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Child interrupted.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Exiting child thread.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class ExtendThread {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>new NewThread(); \/\/ create a new thread<\/p>\n<p>try {<\/p>\n<p>for(int i = 5; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(&#8220;Main Thread: &#8221; + i);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread interrupted.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Main thread exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>This program generates the same output as the preceding version. As you can see, the child thread is created by instantiating an object of <strong>NewThread<\/strong>, which is derived from <strong>Thread<\/strong>. Notice the call to <strong>super( ) <\/strong>inside <strong>NewThread<\/strong>. This invokes the following form of the <strong>Thread <\/strong>constructor:<\/p>\n<p>&nbsp;<\/p>\n<p>public Thread(String <em>threadName<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>threadName <\/em>specifies the name of the thread.<\/p>\n<h2><a name=\"_Toc179309651\"><\/a>Creating Multiple Threads<\/h2>\n<p>So far, you have been using only two threads: the main thread and one child thread. However, your program can spawn as many threads as it needs. For example, the following program creates three child threads:<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Create multiple threads.<\/p>\n<p>class NewThread implements Runnable {<\/p>\n<p>String name; \/\/ name of thread<\/p>\n<p>Thread t;<\/p>\n<p>NewThread(String threadname) {<\/p>\n<p>name = threadname;<\/p>\n<p>t = new Thread(this, name);<\/p>\n<p>System.out.println(&#8220;New thread: &#8221; + t);<\/p>\n<p>t.start(); \/\/ Start the thread<\/p>\n<p>}<\/p>\n<p>\/\/ This is the entry point for thread.<\/p>\n<p>public void run() {<\/p>\n<p>try {<\/p>\n<p>for(int i = 5; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(name + &#8220;: &#8221; + i);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(name + &#8220;Interrupted&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(name + &#8221; exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class MultiThreadDemo {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>new NewThread(&#8220;One&#8221;); \/\/ start threads<\/p>\n<p>new NewThread(&#8220;Two&#8221;);<\/p>\n<p>new NewThread(&#8220;Three&#8221;);<\/p>\n<p>try {<\/p>\n<p>\/\/ wait for other threads to end<\/p>\n<p>Thread.sleep(10000);<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread Interrupted&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Main thread exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>The output from this program is shown here:<\/p>\n<p>New thread: Thread[One,5,main]<\/p>\n<p>New thread: Thread[Two,5,main]<\/p>\n<p>New thread: Thread[Three,5,main]<\/p>\n<p>One: 5<\/p>\n<p>Two: 5<\/p>\n<p>Three: 5<\/p>\n<p>One: 4<\/p>\n<p>Two: 4<\/p>\n<p>Three: 4<\/p>\n<p>One: 3<\/p>\n<p>Three: 3<\/p>\n<p>Two: 3<\/p>\n<p>One: 2<\/p>\n<p>Three: 2<\/p>\n<p>Two: 2<\/p>\n<p>One: 1<\/p>\n<p>Three: 1<\/p>\n<p>Two: 1<\/p>\n<p>One exiting.<\/p>\n<p>Two exiting.<\/p>\n<p>Three exiting.<\/p>\n<p>Main thread exiting.<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, once started, all three child threads share the CPU. Notice the call to <strong>sleep(10000) <\/strong>in <strong>main( )<\/strong>. This causes the main thread to sleep for ten seconds and ensures that it will finish last.<\/p>\n<h2><a name=\"_Toc179309652\"><\/a>Using isAlive( ) and join( )<\/h2>\n<p>As mentioned, often you will want the main thread to finish last. In the preceding examples, this is accomplished by calling <strong>sleep( ) <\/strong>within <strong>main( )<\/strong>, with a long enough delay to ensure that all child threads terminate prior to the main thread. However, this is hardly a satisfactory solution, and it also raises a larger question: How can one thread know when another thread has ended? <strong>Thread <\/strong>provides a means by which you can answer this question. Two ways exist to determine whether a thread has finished. First, you can call <strong>isAlive( ) <\/strong>on the thread. This method is defined by <strong>Thread<\/strong>, and its general form is shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>final boolean isAlive( )<\/p>\n<p>&nbsp;<\/p>\n<p>The <strong>isAlive( ) <\/strong>method returns <strong>true <\/strong>if the thread upon which it is called is still running. It returns <strong>false <\/strong>otherwise. While <strong>isAlive( ) <\/strong>is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called <strong>join( )<\/strong>, shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>final void join( ) throws InterruptedException<\/p>\n<p>&nbsp;<\/p>\n<p>This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread <em>joins <\/em>it. Additional forms of <strong>join( ) <\/strong>allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. Here is an improved version of the preceding example that uses <strong>join( ) <\/strong>to ensure that the main thread is the last to stop. It also demonstrates the <strong>isAlive( ) <\/strong>method.<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Using join() to wait for threads to finish.<\/p>\n<p>class NewThread implements Runnable {<\/p>\n<p>String name; \/\/ name of thread<\/p>\n<p>Thread t;<\/p>\n<p>NewThread(String threadname) {<\/p>\n<p>name = threadname;<\/p>\n<p>t = new Thread(this, name);<\/p>\n<p>System.out.println(&#8220;New thread: &#8221; + t);<\/p>\n<p>t.start(); \/\/ Start the thread<\/p>\n<p>}<\/p>\n<p>\/\/ This is the entry point for thread.<\/p>\n<p>public void run() {<\/p>\n<p>try {<\/p>\n<p>for(int i = 5; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(name + &#8220;: &#8221; + i);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(name + &#8221; interrupted.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(name + &#8221; exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class DemoJoin {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>NewThread ob1 = new NewThread(&#8220;One&#8221;);<\/p>\n<p>NewThread ob2 = new NewThread(&#8220;Two&#8221;);<\/p>\n<p>NewThread ob3 = new NewThread(&#8220;Three&#8221;);<\/p>\n<p>System.out.println(&#8220;Thread One is alive: &#8221;<\/p>\n<p>+ ob1.t.isAlive());<\/p>\n<p>System.out.println(&#8220;Thread Two is alive: &#8221; + ob2.t.isAlive());<\/p>\n<p>System.out.println(&#8220;Thread Three is alive: &#8221; + ob3.t.isAlive());<\/p>\n<p>\/\/ wait for threads to finish<\/p>\n<p>try {<\/p>\n<p>System.out.println(&#8220;Waiting for threads to finish.&#8221;);<\/p>\n<p>ob1.t.join();<\/p>\n<p>ob2.t.join();<\/p>\n<p>ob3.t.join();<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread Interrupted&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Thread One is alive: &#8221; + ob1.t.isAlive());<\/p>\n<p>System.out.println(&#8220;Thread Two is alive: &#8221; + ob2.t.isAlive());<\/p>\n<p>System.out.println(&#8220;Thread Three is alive: &#8221; + ob3.t.isAlive());<\/p>\n<p>System.out.println(&#8220;Main thread exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>Sample output from this program is shown here:<\/p>\n<p>New thread: Thread[One,5,main]<\/p>\n<p>New thread: Thread[Two,5,main]<\/p>\n<p>New thread: Thread[Three,5,main]<\/p>\n<p>Thread One is alive: true<\/p>\n<p>Thread Two is alive: true<\/p>\n<p>Thread Three is alive: true<\/p>\n<p>Waiting for threads to finish.<\/p>\n<p>One: 5<\/p>\n<p>Two: 5<\/p>\n<p>Three: 5<\/p>\n<p>One: 4<\/p>\n<p>Two: 4<\/p>\n<p>Three: 4<\/p>\n<p>One: 3<\/p>\n<p>Two: 3<\/p>\n<p>Three: 3<\/p>\n<p>One: 2<\/p>\n<p>Two: 2<\/p>\n<p>Three: 2<\/p>\n<p>One: 1<\/p>\n<p>Two: 1<\/p>\n<p>Three: 1<\/p>\n<p>Two exiting.<\/p>\n<p>Three exiting.<\/p>\n<p>One exiting.<\/p>\n<p>Thread One is alive: false<\/p>\n<p>Thread Two is alive: false<\/p>\n<p>Thread Three is alive: false<\/p>\n<p>Main thread exiting.<\/p>\n<p>&nbsp;<\/p>\n<p>As you can see, after the calls to <strong>join( ) <\/strong>return, the threads have stopped executing.<\/p>\n<h2><a name=\"_Toc179309653\"><\/a>Thread Priorities<\/h2>\n<p>Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lowerpriority threads. To set a thread\u2019s priority, use the <strong>setPriority( ) <\/strong>method, which is a member of <strong>Thread<\/strong>. This is its general form:<\/p>\n<p>&nbsp;<\/p>\n<p>final void setPriority(int <em>level<\/em>)<\/p>\n<p>&nbsp;<\/p>\n<p>Here, <em>level <\/em>specifies the new priority setting for the calling thread. The value of <em>level <\/em>must be within the range <strong>MIN_PRIORITY <\/strong>and <strong>MAX_PRIORITY<\/strong>. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify <strong>NORM_PRIORITY<\/strong>, which is currently 5. These priorities are defined as <strong>final <\/strong>variables within <strong>Thread<\/strong>. You can obtain the current priority setting by calling the <strong>getPriority( ) <\/strong>method of <strong>Thread<\/strong>, shown here:<\/p>\n<p>&nbsp;<\/p>\n<p>final int getPriority( )<\/p>\n<h2><a name=\"_Toc179309654\"><\/a>Suspending, Resuming, and Stopping Threads<\/h2>\n<p>While the <strong>suspend( )<\/strong>, <strong>resume( )<\/strong>, and <strong>stop( ) <\/strong>methods defined by <strong>Thread <\/strong>seem to be a perfectly reasonable and convenient approach to managing the execution of threads, they must not be used for new Java programs. Here\u2019s why. The <strong>suspend( ) <\/strong>method of the <strong>Thread <\/strong>class is deprecated in Java 2. This was done because <strong>suspend( ) <\/strong>can sometimes cause serious system failures. Assume that a thread has obtained locks on critical data structures. If that thread is suspended at that point, those locks are not relinquished. Other threads that may be waiting for those resources can be deadlocked. The <strong>resume( ) <\/strong>method is also deprecated. It does not cause problems, but cannot be used without the <strong>suspend( ) <\/strong>method as its counterpart. The <strong>stop( ) <\/strong>method of the <strong>Thread <\/strong>class, too, is deprecated in Java 2. This was done because this method can sometimes cause serious system failures. Assume that a thread is writing to a critically important data structure and has completed only part of its changes. If that thread is stopped at that point, that data structure might be left in a corrupted state.<\/p>\n<p>Because you can\u2019t use the <strong>suspend( )<\/strong>, <strong>resume( )<\/strong>, or <strong>stop( ) <\/strong>methods in Java 2 to control a thread, you might be thinking that no way exists to pause, restart, or terminate a thread. But, fortunately, this is not true. Instead, a thread must be designed so that the <strong>run( ) <\/strong>method periodically checks to determine whether that thread should suspend, resume, or stop its own execution. Typically, this is accomplished by establishing a flag variable that indicates the execution state of the thread. As long as this flag is set to \u201crunning,\u201d the <strong>run( ) <\/strong>method must continue to let the thread execute. If this variable is set to \u201csuspend,\u201d the thread must pause. If it is set to \u201cstop,\u201d the thread must terminate. Of course, a variety of ways exist in which to write such code, but the central theme will be the same for all programs. The following example illustrates how the <strong>wait( ) <\/strong>and <strong>notify( ) <\/strong>methods that are inherited from <strong>Object <\/strong>can be used to control the execution of a thread. This example is similar to the program in the previous section. However, the deprecated method calls have been removed. Let us consider the operation of this program. The <strong>NewThread <\/strong>class contains a <strong>boolean <\/strong>instance variable named <strong>suspendFlag<\/strong>, which is used to control the execution of the thread. It is initialized to <strong>false <\/strong>by the constructor. The <strong>run( ) <\/strong>method contains a <strong>synchronized <\/strong>statement block that checks <strong>suspendFlag<\/strong>. If that variable is <strong>true<\/strong>, the <strong>wait( ) <\/strong>method is invoked to suspend the execution of the thread. The <strong>mysuspend( ) <\/strong>method sets <strong>suspendFlag <\/strong>to <strong>true<\/strong>. The\u00a0 <strong>myresume( ) <\/strong>method sets <strong>suspendFlag <\/strong>to <strong>false <\/strong>and invokes <strong>notify( ) <\/strong>to wake up the thread. Finally, the <strong>main( ) <\/strong>method has been modified to invoke the <strong>mysuspend( ) <\/strong>and <strong>myresume( ) <\/strong>methods.<\/p>\n<p>&nbsp;<\/p>\n<p>\/\/ Suspending and resuming a thread for Java 2<\/p>\n<p>class NewThread implements Runnable {<\/p>\n<p>String name; \/\/ name of thread<\/p>\n<p>Thread t;<\/p>\n<p>boolean suspendFlag;<\/p>\n<p>NewThread(String threadname) {<\/p>\n<p>name = threadname;<\/p>\n<p>t = new Thread(this, name);<\/p>\n<p>System.out.println(&#8220;New thread: &#8221; + t);<\/p>\n<p>suspendFlag = false;<\/p>\n<p>t.start(); \/\/ Start the thread<\/p>\n<p>}<\/p>\n<p>\/\/ This is the entry point for thread.<\/p>\n<p>public void run() {<\/p>\n<p>try {<\/p>\n<p>for(int i = 15; i &gt; 0; i&#8211;) {<\/p>\n<p>System.out.println(name + &#8220;: &#8221; + i);<\/p>\n<p>Thread.sleep(200);<\/p>\n<p>synchronized(this) {<\/p>\n<p>while(suspendFlag) {<\/p>\n<p>wait();<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(name + &#8221; interrupted.&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(name + &#8221; exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>void mysuspend() {<\/p>\n<p>suspendFlag = true;<\/p>\n<p>}<\/p>\n<p>synchronized void myresume() {<\/p>\n<p>suspendFlag = false;<\/p>\n<p>notify();<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>class SuspendResume {<\/p>\n<p>public static void main(String args[]) {<\/p>\n<p>NewThread ob1 = new NewThread(&#8220;One&#8221;);<\/p>\n<p>NewThread ob2 = new NewThread(&#8220;Two&#8221;);<\/p>\n<p>try {<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>ob1.mysuspend();<\/p>\n<p>System.out.println(&#8220;Suspending thread One&#8221;);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>ob1.myresume();<\/p>\n<p>System.out.println(&#8220;Resuming thread One&#8221;);<\/p>\n<p>ob2.mysuspend();<\/p>\n<p>System.out.println(&#8220;Suspending thread Two&#8221;);<\/p>\n<p>Thread.sleep(1000);<\/p>\n<p>ob2.myresume();<\/p>\n<p>System.out.println(&#8220;Resuming thread Two&#8221;);<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread Interrupted&#8221;);<\/p>\n<p>}<\/p>\n<p>\/\/ wait for threads to finish<\/p>\n<p>try {<\/p>\n<p>System.out.println(&#8220;Waiting for threads to finish.&#8221;);<\/p>\n<p>ob1.t.join();<\/p>\n<p>ob2.t.join();<\/p>\n<p>} catch (InterruptedException e) {<\/p>\n<p>System.out.println(&#8220;Main thread Interrupted&#8221;);<\/p>\n<p>}<\/p>\n<p>System.out.println(&#8220;Main thread exiting.&#8221;);<\/p>\n<p>}<\/p>\n<p>}<\/p>\n<p>&nbsp;<\/p>\n<p>The output from this program is identical to that shown in the previous section.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Multithreaded Programming &nbsp; Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called&hellip; <\/p>\n","protected":false},"author":1,"featured_media":3478,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[83],"tags":[],"aioseo_notices":[],"amp_enabled":true,"_links":{"self":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3449"}],"collection":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/comments?post=3449"}],"version-history":[{"count":2,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3449\/revisions"}],"predecessor-version":[{"id":3488,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/posts\/3449\/revisions\/3488"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media\/3478"}],"wp:attachment":[{"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/media?parent=3449"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/categories?post=3449"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/softlect.com\/index.php\/wp-json\/wp\/v2\/tags?post=3449"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}