Java thread State, thread stop, thread blocking

Source: Internet
Author: User
Tags thread stop

thread State (five states)

The life cycle of a Java thread consists of 创建,就绪,运行,阻塞,死亡 5 states. A Java thread is always in one of these 5 lifecycle States and can be converted between different states under certain conditions.

Create state (New Thread)
After a thread is created in the Java language using an new operator, the thread is simply an empty object that has some characteristics of the thread, but at this point the system does not allocate resources for it, and the thread is in the created state.

ready State (Runnable)
start()when a thread is started using the method, the system allocates the required resources, except the CPU, to the thread in a ready state. In addition, if a thread executes a yield() method, the thread is temporarily stripped of its CPU resources and re-entered the ready state.

operational Status (Running)
The Java runtime selects a thread in the ready state by scheduling it to occupy the CPU and turn it into a running state. At this point, the system actually executes the thread's run () method.

blocking State (Blocked)
When a running thread cannot continue running for some reason, it goes into a blocking state.
These reasons include the following: when a method of the blocking type of a thread object is executed suspend()、sleep() , the thread object is placed inside a block set (Blocked Pool), waiting to be awakened (execution resume() method) or automatically waking up when it is super-time;
When multiple threads attempt to enter a synchronization region (synchronized) , a thread that fails to enter the synchronization area is placed in the lock Pool until the lock of that synchronization area is acquired and the ready state is reached;
When a thread executes a method of an object, the wait() thread is placed in the object's wait set (wait Pool) until the method of the object is executed notify() , and wait()/notify() the execution of the method requires the thread to first obtain a lock on the object.

death Status (Dead)
The thread run() enters the death state after the method execution ends. In addition, if a thread executes or is a interrupt() stop() method, it also enters the dead state in an abnormally exited manner.

Stop thread (two ways)

1, natural termination: Thread body Normal execution completed
2. External interference

1)线程类中 定义线程体使用的标识。2)线程体使用该标识。3)提供对外的方法,改变该标识。4) 外部根据条件调用该方法即可

Note: Avoid using stop()(具有不安全性)、suspend()(具有固有的死锁现象)、resume() methods such as those provided by the thread class

 PackageThreadState;/** * Stop thread * @author liguodong */ Public  class Demo01 {     Public Static void Main(string[] args) {Study s =NewStudy ();NewThread (s). Start ();//Start        //External interference         for(intI=0;i< -; i++) {if( -==i)//external interference (not very accurate, also depends on CPU){s.stop (); } System.out.println ("Main....-->"+i); }}}class Study implements runnable{//1, Thread class, defines the identity used by the thread body    Private BooleanFlag =true;@Override     Public void Run() {//2, the thread body uses the logo         while(flag) {System.out.println ("Study thread ..."); }           }//3, external provision of methods to change the logo     Public void Stop()    { This. Flag =false; }}
Thread Blocking

1. Join: Merge Thread
2. Yield: Suspend your own thread static method
3. Sleep: Specifies the number of milliseconds that the currently executing thread sleeps (pauses execution) and does not release the lock.
(1) Time-related, such as Countdown
(2) Analog network delay

 PackageThreadState;/** * Thread blocking: Join merge thread */ Public  class Demo02 extends Thread{    @Override     Public void Run() { for(intI=0;i< -; i++) {System.out.println ("Join ..."+i); }       } Public Static void Main(string[] args)throwsinterruptedexception {Demo02 demo =NewDemo02 (); Thread T =NewThread (demo);//FreshmenT.start ();//Ready        //cpu scheduling Operation         for(intI=0;i< -; i++) {if( -==i) {t.join ();//main Blocking} System.out.println ("Main ..."+i); }    }}
 PackageThreadState;/** * Yield: Pause your own thread static method * @author liguodong */ Public  class Demo03 extends Thread{     Public Static void Main(string[] args) {Demo03 demo =NewDemo03 (); Thread T =NewThread (demo);//FreshmenT.start ();//Ready        //cpu scheduling Operation         for(intI=0; i< +; i++) {if(i% -==0)            {//In main thread, pause this thread main                //This method writes in the thread body to stop the thread, if the Demo03 is paused inside the run. Thread.yield ();//static method (there is no strict pause, the CPU may be dispatched to it)} System.out.println ("Main ..."+i); }    }@Override     Public void Run() { for(intI=0; i< +; i++) {System.out.println ("Yield ..."+i); }    }}
 PackageThreadState;ImportJava.text.SimpleDateFormat;ImportJava.util.Date;/** * Sleep: Specifies the number of milliseconds to allow the currently executing thread to hibernate * * (pause execution) without releasing the lock. * Countdown * 1, 10 count, 1 seconds to print a * 2, Countdown * * Public  class Demo04 {     Public Static void Main(string[] args)throwsinterruptedexception {//test01 ();Test02 (); }//Countdown 10, print one in 1 seconds     Public Static void test01()throwsinterruptedexception {intnum =Ten; while(true) {System.out.println (num--); Thread.Sleep ( +);//Pause            if(num<=0)            { Break; }        }    }//Countdown     Public Static void test02()throwsinterruptedexception {//new Date () Current time System.currenttimemillis () also represents the current timeDate EndTime =NewDate (System.currenttimemillis () +Ten* +);//Current time 10 seconds in the future        LongEnd = Endtime.gettime ();//Gets the end time of the long integer type         while(true)        {//OutputSystem.out.println (NewSimpleDateFormat ("HH:mm:ss"). Format (endTime));//Build time of next secondEndTime =NewDate (Endtime.gettime ()- +);//Minus one second endtime decreasing in turn            //wait 1 secondsThread.Sleep ( +);//Pause            ///within 10 seconds to continue or exit end-10000 current time            if(end-10000>endtime.gettime ()) { Break; }        }       }       }
 PackageThreadState;/** * Sleep analog Network delay thread unsafe class results may not be accurate * / Public  class Demo05 {     Public Static void Main(string[] args) {//Real roleWeb12306 Web =NewWeb12306 ();//AgentThread T1 =NewThread (web,"Demacia"); Thread t2 =NewThread (web,"Katrina"); Thread t3 =NewThread (web,"Chancellor of the state of Lourdes");//Start threadT1.start ();        T2.start ();    T3.start (); }}class Web12306 implements runnable{Private intnum = -;@Override     Public void Run() { while(true)        {if(num<=0)            { Break;//Jump out of the loop}Try{Thread.Sleep ( -); }Catch(Interruptedexception e)            {E.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"Got to the bottom."+num--+"Zhang"); }    }}

Java thread State, thread stop, thread blocking

Related Article

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.