Java Learning Class 28th session (Multi-threaded (vii))-Stop-threaded Multi--threaded face question

Source: Internet
Author: User


Master key

/*
* Wait and sleep differences?
* 1.wait can specify time and can not specify
* Sleep must specify a time
* 2. In the synchronization, the CPU operation right and the lock processing is different
* Wait releases run right, release lock sleep release run right, do not release lock
*/

There are more than one thread running in sync, but only one can get the lock, so there is only one that can run


One, the way to stop the thread

It is not possible to keep threads executing. So the thread needs to stop


1. Define the Loop end tag

In general, thread execution code is circular, and it is possible to end a task simply by controlling the loop

2. Using Interrupt (interrupt)

Ends the frozen state of the thread. Bring the thread back to the execution state

Ps:stop is out of date, No.

The First way : (often used)

Class Stopthread implements Runnable{private Boolean flag = True;public void Run () {while (flag) {System.out.println ( Thread.CurrentThread (). GetName () + "---");}} public void Changeflag () {flag = false;}} public class Main{public static void Main (string[] args) {stopthread s = new Stopthread (); thread T1 = new thread (s); Thread t2 = new Thread (s); T1.start (); T2.start (); int i = 0;while (true) {if (++i = =)//i reaches 20 after the end of all threads {S.changeflag (); System.out.println ("Main.main" +i); System.out.println ("Final");}}

Disadvantages:

Class Stopthread implements Runnable{private Boolean flag = true;public synchronized void run () {while (flag) {try {wait ();} catch (Interruptedexception e) {//Todo:handle exceptionSystem.out.println (Thread.CurrentThread (). GetName () + "..." +e );} System.out.println (Thread.CurrentThread (). GetName () + "-++--");}} public void Changeflag () {flag = false;}}

The main thread is finished. T0 T1 direct Wait (). Assume that the thread is in a frozen state. Cannot read the tag, so it introduces another way to end the thread


Another way: Interrupt

Forces the thread to resume from the frozen state to the execution state. bring the thread back to a state with CPU execution eligibility. However , an interrupt exception will occur (Interruptexception)

Class Stopthread implements Runnable{private Boolean flag = true;public synchronized void run () {while (flag) {try {wait ();} catch (Interruptedexception e) {//Todo:handle exceptionSystem.out.println (Thread.CurrentThread (). GetName () + " ... "+e); flag = false;//pay attention to the processing, not adding this will cause the thread to continue waiting. Main thread End T1 T2 not end}system.out.println (Thread.CurrentThread (). GetName () + "-++--");}} public void Changeflag () {flag = false;}} public class Main{public static void Main (string[] args) {stopthread s = new Stopthread (); thread T1 = new thread (s); Thread t2 = new Thread (s); T1.start (); T2.start (); int i = 0;while (true) {if (++i = =)//i reaches 20 after the end of all threads {//s.changeflag (); T1.interrupt (); T2.interrupt (); break;} System.out.println ("Main.main" +i); System.out.println ("Final");}}


Second, the Guardian thread

Setdaemon (Boolean)

public class Main{public static void Main (string[] args) {stopthread s = new Stopthread (); thread T1 = new thread (s); Thread t2 = new Thread (s); T1.start (); T2.setdaemon (TRUE);//daemon thread, can be understood as the characteristics of the rear antenna path//After the antenna path: the execution and the foreground thread, and the CPU Snatch execution//           end: The foreground thread must end manually, the background thread assumes that all the prerequisite threads are finished, The background thread also follows the end of T2.start (); int i = 0;while (true) {if (++i = =)//i reaches 20 after the end of all threads {//s.changeflag (); T1.interrupt ();//t2.interrupt (); break;} System.out.println ("Main.main" +i); System.out.println ("Final");}}

The daemon thread is simple to understand: Say (League of Legends) LOL. Our heroes need to guard our towers, the towers are gone, and the daemons are not necessary.

Iii. Other methods of threading

1.join ()

2.setPriority ()


Class Demo implements Runnable{public void Run () {for (int i = 0;i<20;i++) System.out.println (Thread.CurrentThread (). GetName () + "..." +i);}} public class Main{public static void Main (string[] args) throws Exception{demo D = new Demo (); thread T1 = new Thread (d); Thread t2 = new Thread (d); T1.start (); T1.join ();//t1 thread to request an increase in. Perform. That is, T1, T2 and the main thread can not be executed. For the time being a thread, it is necessary to use the Join Method T2.start ();//Assuming that the join is placed behind T2.start (), then the main thread waits only for T1 to execute, while T1 and T2 scramble for execution for (int i = 0;i<20;i++) System.out.println (Thread.CurrentThread (). GetName () + "..." +i);}}

Priority: SetPriority

Class Demo implements Runnable{public void Run () {for (int i = 0;i<20;i++) System.out.println (Thread.CurrentThread (). ToString () + "..." +i);}} public class Main{public static void Main (string[] args) throws Exception{demo D = new Demo (); thread T1 = new Thread (d); Thread t2 = new Thread (d); T1.start (); T2.start (); t2.setpriority (thread.max_priority);//thread.min_priority Priority minimum 1// Thread.max_priority effective level Max 10//thread.norm_priority default priority 5for (int i = 0;i<20;i++) System.out.println ( Thread.CurrentThread () + "..." +i);}}

3. Thread groups

Put 10 threads in a group. Assume that this set of threads is interrupted. Then all 10 of these threads are broken.

4.yield () pauses the currently running thread and runs other threads


Class Demo implements Runnable{public void Run () {for (int i = 0;i<20;i++) {System.out.println (Thread.CurrentThread (). ToString () + "..." +i); Thread.yield ();}}}

public class Main{public static void Main (string[] args) throws Exception{new thread ()//Line Cheng Zi class {public void Run () {for (int i = 0;i<20;i++) {System.out.println (Thread.CurrentThread (). GetName () + "x =" +i);}}}. Start (); for (int i = 0;i<20;i++) {System.out.println (Thread.CurrentThread (). GetName () + "y =" +i);} Runnable r = new Runnable () {public void run () {for (int i = 0;i<20;i++) {System.out.println (Thread.CurrentThread ()). Getn Ame () + "z =" +i);}}; New Thread (R). Start ();}}

Multi-threaded interview questions:

1.

Class Text implements Runnable{public void Run (Thread t) {}}//failed to compile? What is the hypothetical failure error?

failed with overwrite of Run method not implemented

Change Law One:

Abstract class Text implements Runnable{public void Run (Thread t) {}}

Change method Two: overload, cover


Class Text implements Runnable{public void Run () {System.out.println ("Text.run () 1");} public void Run (Thread t) {System.out.println ("Text.run () 2");}}
2.

public class Main{public static void Main (string[] args) throws Exception{new Thread (new Runnable () {public void run () {// TODO auto-generated Method StubSystem.out.println ("Runnable Run");}) {public void Run () {System.out.println ("Thread Run");}}. Start ();//Can this code compile pass? Suppose you can print which sentence}}
Print thread Run
with subclasses as the main, no subclasses are dominated by the parent class




Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Java Learning Class 28th session (Multi-threaded (vii))-Stop-threaded Multi--threaded face question

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.