Dark Horse Programmer _ Diary 19_java Multithreading (ix)

Source: Internet
Author: User

——-Android Training, Java training, look forward to communicating with you! ———-

1 Stopping a thread

Principle: Let the Run method end. The Run method usually defines the loop structure, so it is possible to control the loop structure.

The Stop method is obsolete.

How to control the loop structure??
1 Defining the end tag
2 The program cannot end when the thread is in a frozen state without executing the tag.
You can loop, exit the freeze state normally, or force the end of the freeze state.
Force end Freeze State: Interrupt (); The purpose is to force the thread to resume from the frozen state to the running state.
However, interruptedexception exceptions can occur.

//1 define end tag End thread class stopthread implements Runnable{    BooleanFlag =true;//define tag control loop structure    //Overwrite the Run method     Public voidRun () { while(flag) {System.out.println (Thread.CurrentThread (). GetName () +"... run");//Print the name of the thread that called the Run method}    }//change marker     Public voidChangeflag () {flag =false; }} class stopthreaddemo{     Public Static voidMain (string[] args) {Stopthread St =NewStopthread ();//Create an object for the class that implements the Runnable interfaceThread T1 =NewThread (ST);//Build thread 1Thread t2 =NewThread (ST);//Build thread 2T1.start ();//Start thread 1, call the Run methodT2.start ();//Start thread 2, call the Run method        //define a loop, wait until thread 1 and thread 2 run for a while, the main thread then changes the flag flag to False        intnum =0; while(true)        {if(num++ = = -) {St.changeflag ();//Change the tag of the while loop in the Run method                 Break;//Change the mark to immediately end the while loop of the main thread} System.out.println (Thread.CurrentThread (). GetName () +"... run"+num);//Show the results of the main thread execution} System.out.println ("Over");//Indicates that the main thread has finished executing}}

Partial Run Result:
Thread-0...run
Thread-0...run
Thread-1...run
Thread-0...run
Main......run50
Thread-0...run
Thread-1...run
Over

From the console, you can see that when the main thread runs a while loop 50 times,
Jumps out of the while loop and executes the end.
and thread 1 and thread are finished.

Here's a look at how to end a thread when the thread is in a frozen state

 class stopthread implements Runnable{    BooleanFlag =true;//define tag control loop structure    //Overwrite the Run method, note that wait can only be used in synchronization     PublicSynchronizedvoidRun () { while(flag) {Try{Wait (); }Catch(Interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName () +"... Exception "); Flag =false;//In the frozen state, immediately change the mark, end the loop, end the run, end the thread} System.out.println (Thread.CurrentThread (). GetName () +"... run");//Print the name of the thread that called the Run method}    }} class stopthreaddemo{     Public Static voidMain (string[] args) {Stopthread St =NewStopthread ();//Create an object for the class that implements the Runnable interfaceThread T1 =NewThread (ST);//Build thread 1Thread t2 =NewThread (ST);//Build thread 2T1.start ();//Start thread 1, call the Run methodT2.start ();//Start thread 2, call the Run method        //define a loop, wait until thread 1 and thread 2 run for a while, the main thread then changes the flag flag to False        intnum =0; while(true)        {if(num++ = = -) {t1.interrupt ();//Force clear the freezing state of thread 1T2.interrupt ();//Force clear the freezing state of thread 1                 Break;//Change the mark to immediately end the while loop of the main thread} System.out.println (Thread.CurrentThread (). GetName () +"... run"+num);//Show the results of the main thread execution} System.out.println ("Over");//Indicates that the main thread has finished executing}}

When you change the Run method to the following

publicvoidrun()    {        while(flag)        {            try            {                this.wait();            }            catch (InterruptedException e)            {            }            System.out.println(Thread.currentThread().getName()+"...run");//打印调用run方法的线程名        }    }

The running results show:
Thread 1 and Thread 21 call the Run method into a frozen state.
And, until the main thread ends, they are not finished.

In this respect, we use the interrupt method to force the freezing state of the interrupt thread.

Summarize:
Special cases:
When the thread is in a frozen state.
The tag is not read. Then the thread will not end.

When there is no specified way to get the frozen thread back to the running state, then the freeze needs to be cleared.
Forces the thread to revert to the running state. This makes it possible to manipulate the tag to end the thread.

The thread class provides the method interrupt ();

2 threads in some common methods 2.1 daemon threads

setDaemon(boolean): The thread is marked as a background thread, and the background thread is the same as the foreground thread, with the same execution run,
Only at the end, there is a difference, the background thread will end automatically after the current station thread has finished running.
Change the example of the front end thread.

 class stopthread implements Runnable{    BooleanFlag =true;//define tag control loop structure    //Overwrite the Run method,     Public voidRun () { while(flag) System.out.println (Thread.CurrentThread (). GetName () +"... run");//Print the name of the thread that called the Run method}} class stopthreaddemo{     Public Static voidMain (string[] args) {Stopthread St =NewStopthread ();//Create an object for the class that implements the Runnable interfaceThread T1 =NewThread (ST);//Build thread 1Thread t2 =NewThread (ST);//Build thread 2T1.setdaemon (true);//Mark thread 1 as a background threadT2.setdaemon (true);//Mark thread 2 as a background threadT1.start ();//Start thread 1, call the Run methodT2.start ();//Start thread 2, call the Run method        //define a loop, wait until thread 1 and thread 2 run for a while, the main thread then changes the flag flag to False        intnum =0; while(true)        {if(num++ = = -)            { Break;//Change the mark to immediately end the while loop of the main thread} System.out.println (Thread.CurrentThread (). GetName () +"... run"+num);//Show the results of the main thread execution} System.out.println ("Over");//Indicates that the main thread has finished executing}}

Run results
Thread-0...run
Thread-1...run
Main......run50
Thread-1...run
Thread-0...run
Thread-1...run
Over
Thread-1...run
The results show that thread 1 and thread 2 end immediately after the main thread ends

2.2 Join method

Join method: The CPU execution is robbed until the thread execution ends before the CPU execution is discarded.
For example, when the main thread touches t1.join (), the main thread hangs, letting the CPU give the thread T1,
The main thread does not restart after the T1 ends.
Examples are shown below.

 class Join implements Runnable{     Public voidRun () { for(inti =0; I < -; i++) {System.out.println (Thread.CurrentThread (). toString () +"is running ..."+i);            Thread.yield (); }    }} class joindemo {     Public Static voidMain (string[] args) throws Interruptedexception {Join J =NewJoin (); Thread T1 =NewThread (j); Thread t2 =NewThread (j);//t1.setpriority (thread.min_priority);T1.start ();//t1.setpriority (thread.max_priority);        //t1.join ();//thread T1 call the Join method to observe the main print resultT2.start ();/ * for (int i = 0;i <, i++) System.out.println (Thread.CurrentThread (). GetName () + "is running .... ... "+i); * *System.out.println ("Over"); }}

The result of the operation shows that the T2 and main thread are not started until the threads T1 run.

Summary:
Join (): What do you mean? Wait for the thread to end. When a thread executes to the. Join method of B, a is frozen.
A When do you run it? When B is finished, a will be eligible to run. Join a thread, you can complete a temporary join execution of a thread.

2.3 Yield method

Yield: A temporary pause that allows the thread to release execution rights.
Add Thread.yield () inside the Run method;
The result is:
Thread[thread-0,5,main]is running ... 0
Thread[thread-1,5,main]is running ... 1
Thread[thread-0,5,main]is running ... 1
Thread[thread-0,5,main]is running ... 2
Thread[thread-0,5,main]is running ... 3
Thread[thread-1,5,main]is running ... 2
Thread[thread-0,5,main]is running ... 4
Thread[thread-1,5,main]is running ... 3
Thread[thread-0,5,main]is running ... 5
Thread[thread-1,5,main]is running ... 4
Thread[thread-0,5,main]is running ... 6
Thread[thread-1,5,main]is running ... 5
Two threads are executing alternately.

Yield () achieves the average CPU allocation effect

3 Thread groups and priorities

Thread Group: Who opens it belongs to WHO. Examples are as follows:
Thread[thread-0,10,main]is running ... 49
Thread[thread-1,5,main]is running ... 49
The default priority is 5, only 1,5,10 most obvious

publicstaticfinalint1;publicstaticfinalint10;publicstaticfinalint1;
4 The difference between wait and sleep

The difference between wait and sleep:
Wait: Releases the CPU execution and releases the sync lock.
Sleep: Releases the CPU execution and does not release the sync lock.

Black Horse Programmer _ Diary 19_java Multithreading (ix)

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.