[Java Thread]sleep,join,interrupt parsing __java

Source: Internet
Author: User
Tags thread class

Start today with a deep study of Java threads, starting with the 3 functions of sleep,join,interrupt.

Let's take a look at the functions of these 3 functions.

1,sleep: Is a static method of the thread class, which is to block the current thread, the function's argument is blocking time, in milliseconds.
2,interrupt: in the thread.
3,join: The role is to keep two threads synchronized. For example, there are a,b two threads, and if A.join () is invoked in B, it means that a thread executes before it starts executing B thread.

Nonsense do not say, look at the example of learning to change it. ========================sleep article ========================

Example to implement the function: Start a thread, every second to perform a print

Look at the code below:

Package Lxcjie;

Import Java.util.Calendar;

public class Sleepdemo extends thread {public

    static void Main (string[] args) {
        //create thread
        sleepdemo sleep = new Sleepdemo ();
        Thread starts executing
        sleep.start ();
    }

    public void Run () {
        try {
            ///Do an infinite loop, output once per second
            (true) {//
                thread interrupts 1 seconds to continue sleep
                (1000);
                System.out.println (GetTime () + "  " + getName () + "is Running");
            }
        catch (Interruptedexception e) {
            E.printstacktrace ();
        }

    To make it easier to understand, precede the print content with the current time
    private String getTime () {
        Calendar rightnow = Calendar.getinstance ();
        Rightnow.settimeinmillis (System.currenttimemillis ());
        Return Rightnow.get (Calendar.hour) + ":"
                + rightnow.get (calendar.minute) + ":"
                + rightnow.get ( Calendar.second);
    }

Look at the execution results:

As you can see, the content is printed once every second, as we expect, OK. =================interrupt article =================

Example to implement the function: print 5 times information after the interrupt thread

Look at the code below:

Package Lxcjie;

public class Interruptdemo extends Thread {public

    static void Main (string[] args) throws Interruptedexception {
        / /create thread
        interruptdemo sleep = new Interruptdemo ();
        Start thread
        sleep.start ();

        Main thread interrupt 5 seconds
        Thread.Sleep (5000);
        The sleep child thread was interrupted
        sleep.interrupt ();
    }

    public void Run () {
        try {
            //do an infinite loop, printing one message per second
            (true) {sleep
                (1000);
                System.out.println (GetName () + "is Running");
            }
        catch (Interruptedexception e) {
            //print a message after
            the terminal System.out.println (GetName () + "is interrupted");
            return;}}

Look at the execution results:

OK, the message was interrupted after printing 5 times. ========================join article ========================

The sleep and interrupt functions belong to the more intuitive two functions in the thread, and the example should be understood.
For the join this function, at least for me, more abstract, so the following specific analysis.

As mentioned earlier, the function of the join function is to keep two threads synchronized, in other words, add a sequence of execution to two threads.
A bit more verbose, that is, if the join function is not added, A and b two threads are executed concurrently, add the Join function, A and b two threads
The sequence specified by the program executes sequentially.

For verification, let's look at an example to see what happens when there is no join function:

Package Lxcjie; public class Joindemo {public static void main (string[] args) throws Interruptedexception {//create Sleepthread Strand
        Cheng Sleepthread sleep = new Sleepthread ("Mysleepthread");
        
        Creates a jointhread thread and passes the above Sleepthread thread as a parameter to the Jointhread join = new Jointhread ("Myjointhread", sleep);
        Start 2 Child threads Sleep.start ();

        Join.start ();
        Main thread Interrupt 3 seconds Thread.Sleep (3000);
    Sleepthread thread is interrupted sleep.interrupt (); }//Create a thread class that functions as follows://1, print a message every 1 seconds//2, if the thread is interrupted, print interrupted information class Sleepthread extends thread {public Sleepthread (Str
    ing name) {super (name);
            public void Run () {while (true) {try {1000);
                catch (Interruptedexception e) {System.out.println (">>>" + getName () + "is interrupted");
            Return
        } System.out.println (GetName () + "is Running");
}
    }//Create another thread class, which functions as follows://1, call the Join function, keep in sync with the incoming Sleepthread thread//That is, after sleepthread execution of the thread, Jointhread continues to execute//2, printing a message every 1 seconds/

    3, if the thread is interrupted, print interrupted information class Jointhread extends thread {private Sleepthread sleep = null;
        Sleepthread is used as a constructor parameter for thread synchronization operations public Jointhread (String name, Sleepthread sleep) {super (name);
    This.sleep = sleep;

            public void Run () {try {//) to get a more intuitive understanding of the join function, let's comment it out to see what happens//this.sleep.join ();
                while (true) {sleep (1000);
            System.out.println (GetName () + "is Running");
        The catch (Interruptedexception e) {System.out.println ("interrupted");
 }
    }
}

What the hell happened, let's take a look at the execution results:

As you can see, two threads start at the same time, and after the Mysleepthread thread is interrupted, only the myjointhread thread executes.
In other words, the execution of two threads is completely free of any connection.

Let's remove the annotation section below:

Package Lxcjie; public class Joindemo {public static void main (string[] args) throws Interruptedexception {//create Sleepthread Strand
        Cheng Sleepthread sleep = new Sleepthread ("Mysleepthread");
        
        Creates a jointhread thread and passes the above Sleepthread thread as a parameter to the Jointhread join = new Jointhread ("Myjointhread", sleep);
        Start 2 Child threads Sleep.start ();

        Join.start ();
        Main thread Interrupt 3 seconds Thread.Sleep (3000);
    Sleepthread thread is interrupted sleep.interrupt (); }//Create a thread class that functions as follows://1, print a message every 1 seconds//2, if the thread is interrupted, print interrupted information class Sleepthread extends thread {public Sleepthread (Str
    ing name) {super (name);
            public void Run () {while (true) {try {1000);
                catch (Interruptedexception e) {System.out.println (">>>" + getName () + "is interrupted");
            Return
        } System.out.println (GetName () + "is Running");
}
    }//Create another thread class, which functions as follows://1, call the Join function, keep in sync with the incoming Sleepthread thread//That is, after sleepthread execution of the thread, Jointhread continues to execute//2, printing a message every 1 seconds/

    3, if the thread is interrupted, print interrupted information class Jointhread extends thread {private Sleepthread sleep = null;
        Sleepthread is used as a constructor parameter for thread synchronization operations public Jointhread (String name, Sleepthread sleep) {super (name);
    This.sleep = sleep;
            The public void run () {try {//note is removed, see the result ...)

            This.sleep.join ();
                while (true) {sleep (1000);
            System.out.println (GetName () + "is Running");
        The catch (Interruptedexception e) {System.out.println ("interrupted");
 }
    }
}

Let's take a look at the result of adding a join:

What we see. At the beginning, only Mysleepthread was executed, and when Mysleepthread was interrupted,
Myjointhread was executed. See here, the function of the join function is very intuitive.

All right, I'll learn to come here today and share with you the results of our study.

Continue to study hard ...

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.