The 18th chapter the life cycle of multithreading----threads

Source: Internet
Author: User

Threads have a life cycle that contains 7 states, namely, birth status, ready state, running state, waiting state, hibernation state, blocking state, and dead busy state.

1, the sleep of the thread

For example, create a Sleepmethodtest class in the project that inherits the JFrame class, implements the ability to automatically draw segments in the form, and sets the color for the segments, which are randomly generated.

Importjava.awt.*;ImportJava.util.*;Importjavax.swing.*;
Public classSleepmethodtestextendsJFrame { Private Static Final LongSerialversionuid = 1L; PrivateThread t; Private Staticcolor[] color ={color.black, Color.Blue, Color.cyan,//define color array color.green, Color.orange, Color.yellow, Color.Red, Color.pink, Color.light_gray}; Private Static FinalRandom Rand =NewRandom ();//creating random Objects Private StaticColor GetC () {//ways to get random color values returnColor[rand.nextint (color.length)]; } Publicsleepmethodtest () {T=NewThread (NewRunnable () {//creating an anonymous thread object intx = 30;//Defining initial coordinates inty = 50; Public voidRun () {//overriding thread interface methods while(true) {//Infinite Loops try {thread.sleep (100);//Thread hibernation 0.1 sec} catch (Interruptedexception e) { E.printstacktrace (); } //get component Drawing context objectGraphics graphics =getgraphics (); Graphics.setcolor (GetC ());//Set Drawing Colors//draw a line and increment the vertical coordinateGraphics.drawline (x, Y, y++,); if(Y >= 80) {y= 50; } } } }); T.start ();//Start Thread } Public Static voidMain (string[] args) {init (NewSleepmethodtest (), 100, 100); } //methods for initializing the program interface Public Static voidInit (JFrame frame,intWidthintheight) {frame.setdefaultcloseoperation (jframe.exit_on_close); Frame.setsize (width, height); Frame.setvisible (true); }}

2. Join the thread

If the current program is a multithreaded program, if there is a thread A, now you need to insert thread B, and require thread B to finish first, and then continue to execute thread A, you can use the thread class in the join () method to complete.

For example: Create a Jointest class in your project that inherits the JFrame class. The instance consists of two progress bars, the progress bar is controlled by the thread, and the join () method is used to make the above progress bar wait until the following progress bar is completed before it can continue.

Importjava.awt.*;Importjavax.swing.*; Public classJointestextendsJFrame {Private Static Final LongSerialversionuid = 1L; PrivateThread Threada;//Define two threads    PrivateThread threadb; FinalJProgressBar ProgressBar =NewJProgressBar ();//define two progress bar components    FinalJProgressBar progressBar2 =NewJProgressBar (); intCount = 0;  Public Static voidMain (string[] args) {init (NewJointest (), 100, 100); }         Publicjointest () {Super(); //set the progress bar to the North of the formGetcontentpane (). Add (ProgressBar, Borderlayout.north); //set the progress bar to the South of the formGetcontentpane (). Add (ProgressBar2, Borderlayout.south); Progressbar.setstringpainted (true);//set the progress bar to display numeric charactersProgressbar2.setstringpainted (true); //initializing the thread real example using the anonymous inner class formThreada =NewThread (NewRunnable () {intCount = 0;  Public voidRun () {//override the Run () method                 while(true) {Progressbar.setvalue (++count);//set the current value of the progress bar                    Try{Thread.Sleep (100);//leave thread a dormant for 100 millisecondsThreadb.join ();//make thread B call the Join () method}Catch(Exception e) {e.printstacktrace ();        }                }            }        }); Threada.start (); //start thread ATHREADB =NewThread (NewRunnable () {intCount = 0;  Public voidrun () { while(true) {Progressbar2.setvalue (++count);//set the current value of the progress bar                    Try{Thread.Sleep (100);//Leave thread b dormant for 100 milliseconds}Catch(Exception e) {e.printstacktrace (); }                    if(count = = 100)//When the count variable grows to 100                         Break;//Jump out of the loop                }            }        }); Threadb.start (); //start thread B    }        //set the form's various property methods     Public Static voidInit (JFrame frame,intWidthintheight)        {frame.setdefaultcloseoperation (jframe.exit_on_close);        Frame.setsize (width, height); Frame.setvisible (true); }}

3. Interrupt of Thread

The Stop () method was used in the past, but now the version of the JDK has already abolished the stop () method, it is not recommended to use the Stop () method to stop a thread to run, now advocates the use of the Run () method in the form of an infinite loop, and then use a Boolean tag to control the loop stop.

For example: Create a interruptedswing () method in a project that implements the Runnable interface, creates a progress bar, and uses the interrupted () method in the thread that represents the progress bar.

Importjava.awt.*;Importjavax.swing.*; Public classInterruptedswingextendsJFrame {Private Static Final LongSerialversionuid = 1L;        Thread thread;  Public Static voidMain (string[] args) {init (NewInterruptedswing (), 100, 100); }         Publicinterruptedswing () {Super(); FinalJProgressBar ProgressBar =NewJProgressBar ();//Create a progress barGetcontentpane (). Add (ProgressBar, Borderlayout.north); Place the progress bar in the appropriate position on the form progressbar.setstringpainted (true);//set the number to display on the progress barThread =NewThread (NewRunnable () {intCount = 0;  Public voidrun () { while(true) {Progressbar.setvalue (++count);//set the current value of the progress bar                    Try{Thread.Sleep (1000);//To keep a thread dormant for 1000 hao seconds//Catching interruptedexception Exceptions}Catch(interruptedexception e) {System.out.println ("Current line program is interrupted");  Break;        }                }            }        }); Thread.Start (); //Start ThreadThread.Interrupt ();//break thread in    }         Public Static voidInit (JFrame frame,intWidthintheight)        {frame.setdefaultcloseoperation (jframe.exit_on_close);        Frame.setsize (width, height); Frame.setvisible (true); }    }

The 18th chapter the life cycle of multithreading----threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.