Java 22-7 Multi-thread method for controlling threading

Source: Internet
Author: User
Tags thread class thread stop

Thread hibernation (let the thread rest for a while and then run)
public static void sleep (long Millis)

Add the method to your custom thread class.

After the change, run the test class, and the result is that after each round of execution, rest for 1 seconds (which is set to hibernate for 1 seconds) and then round.

Round: (If the test class calls 3 threads, then it is run randomly 3 times for a round)

Such as:

Husky: 1, Date: Wed Oct 21:01:19 CST 2016
Short-tailed Cat: 1, Date: Wed Oct 21:01:19 CST 2016
Samoyed: 1, Date: Wed Oct 21:01:19 CST 2016

Rest for 1 seconds and continue:

Samoyed: 2, Date: Wed Oct 21:01:20 CST 2016
Husky: 2, Date: Wed Oct 21:01:20 CST 2016
Short-tailed Cat: 2, Date: Wed Oct 21:01:20 CST 2016

1  Public classThreadsleepextendsThread {2 @Override3      Public voidrun () {4          for(intx = 0; x < 100; X + +) {5System.out.println (GetName () + ":" + x + ", Date:" +NewDate ());6             //Sleeping7             //Take a little rest for 1 seconds8             Try {9                 Thread.Sleep ()///Because the parent class does not throw an exception, it has to Try{}catch () {} Ten}Catch(interruptedexception e) { One e.printstacktrace (); A             } -         } -     } the}


Thread Join
Public final void Join (): Waits for the thread to terminate. This method is added on the test class.

That is, you have to wait for the thread to run until the other thread runs.

The following code is, husky first count 0-99, Samoyed and short-tailed cat to run ... Two ha true 6

 Public classThreadjoindemo { Public Static voidMain (string[] args) {threadjoin tj1=NewThreadjoin (); Threadjoin tj2=NewThreadjoin (); Threadjoin tj3=NewThreadjoin (); Tj1.setname (Husky); Tj2.setname (Samoyed); Tj3.setname ("Short-tailed Cat");        Tj1.start (); Try{ tj1.join ();//Because the parent class does not throw an exception, it has to Try{}catch () {} }Catch(interruptedexception e) {e.printstacktrace ();        } tj2.start ();    Tj3.start (); }}

Thread comity
public static void yield (); : Pauses the currently executing thread object and executes other threads.

Let the execution of multiple threads more harmonious, but can not rely on it to ensure full harmony (that is, husky run once, Samoyed run once, short tail cat run once).

This method can not be fully guaranteed, it is possible to run the husky several times. Two Kazakhstan continued 6.

The method is added in the test class:

1  Public classThreadyieldextendsThread {2 @Override3      Public voidrun () {4          for(intx = 0; x < 100; X + +) {5System.out.println (GetName () + ":" +x);6 Thread.yield ();7         }8     }9}

Daemon Threads
Public final void Setdaemon (Boolean on): marks the thread as either a daemon thread or a user thread. When a running thread is a daemon thread, the Java virtual machine exits. The method must be called before the thread is started.

It is easy to understand that the daemon thread is used to protect other non-daemon threads, and if other non-daemons are stopped, the daemon itself must stop

(The protector hangs up, the keeper has to hang, but the keeper gets the message, so the protector hangs up, and the Guardian continues to hang it several times)

Code:

1 //in this code, Liu Bei a run finished, Zhang Fei Guan Yu followed the run several times, stopped2  Public classThreaddaemondemo {3      Public Static voidMain (string[] args) {4Threaddaemon TD1 =NewThreaddaemon ();5Threaddaemon TD2 =NewThreaddaemon ();6 7Td1.setname ("Guan Yu");8Td2.setname ("Zhang Fei"));9 Ten         //Setting the daemon thread One        Td1.setdaemon (true);  A        Td2.setdaemon (true);  -  - Td1.start (); the Td2.start (); -  -Thread.CurrentThread (). SetName ("Liu Bei"); -          for(intx = 0; x < 5; X + +) { +System.out.println (Thread.CurrentThread (). GetName () + ":" +x); -         } +     } A}

Let's get another picture: Tank Wars


Break Thread in

Public final void Stop (): Let the thread stop, obsolete, but can also be used.

Instead of stop:

Public Void Interrupt (): Middle Break thread. Terminates the state of the thread and throws a interruptedexception.

Custom multithreaded classes:

 Public classThreadstopextendsThread {@Override Public voidrun () {System.out.println ("Start execution:" +NewDate ()); //sleep for 10 seconds        Try{Thread.Sleep (10000); } Catch(interruptedexception e) {//e.printstacktrace ();SYSTEM.OUT.PRINTLN ("Thread has been terminated"); } System.out.println ("End Execution:" +NewDate ()); }}

Test class:

1  Public classThreadstopdemo {2      Public Static voidMain (string[] args) {3Threadstop ts =Newthreadstop ();4         Try {5Thread.Sleep (3000);6             //Ts.stop (); //after 3 seconds, close the threadstop thread,7            ts.interrupt ();The thread is disconnected. Putthe state of the threadTerminate, and throw a interruptedexception8}Catch(interruptedexception e) {9 e.printstacktrace ();Ten         } One     } A}

public void Interrupt (): The result of the execution:

    Start execution: Wed Oct 21:58:44 CST 2016
    The thread is terminated.
    End of execution: Wed Oct 21:58:47 CST 2016

Java 22-7 Multi-thread method for controlling threading

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.