Java Learning Lesson 28th (Multithreading (vii))-stopping threads and multithreaded faces questions

Source: Internet
Author: User


Focus on mastering

/*
* Wait and sleep difference?
* 1.wait can be specified time or not specified
* Sleep must specify a time
* 2. In synchronization, the CPU execution and lock processing are different
* Wait release execution, release lock sleep release execution right, no release lock
*/

There is more than one thread in the synchronization, but only one can get the lock, so only one can be executed.


One, the way to stop the thread

It is not possible to keep the thread running, so the thread needs to stop


1. Define the Loop end tag

In general, thread-running code is circular and can end a task as long as the loop is controlled

2. Using Interrupt (interrupt)

Ends the frozen state of a thread, bringing the thread back to the running state

Ps:stop is out of date, No.

The First way : (Common)

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 End All Threads {S.changeflag () after reaching 20; 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 directly wait (), if the thread is frozen, it cannot read the tag, so the second way to end the thread is introduced


The second way: interrupt

Force a thread from a frozen state to a running state, returning the thread to a state with CPU execution, but with an interrupt exception (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;//Note processing, not adding this will cause the thread to continue to wait, the main thread ends 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 to end 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 after antenna path//After antenna path features: Run and foreground thread, and CPU snatch execution//           end: Foreground thread must end manually, background thread if 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: for example (League of Legends) LOL, our heroes need to guard our towers, the tower is gone, and the daemon doesn't have to exist.

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 apply to join in, run, that is, T1, T2 and the main thread can not be executed,//temporary if a thread, it is necessary to use the Join Method T2.start () ;//If the join is placed behind T2.start (), then the main thread waits only for T1 to complete, while T1 and T2 compete against each other 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, and if you break this set of threads, then all 10 of these threads will break

4.yield () pauses the currently executing thread and executes 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 if the 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? If you can print which sentence}}
Print thread Run
with subclasses as the main, no subclasses are dominated by the parent class




Java Learning Lesson 28th (Multithreading (vii))-stopping threads and multithreaded faces questions

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.