Java Multithreading---Wait () & Join ()

Source: Internet
Author: User

Off Topic:

The interrupt () method does not interrupt a normal running thread!!!

Class MyThread extends thread{    @Override public    void Run () {for        (int i = 0; i <; i++) {            System.out . println (i);}}    public class Waittest {public    static void Main (string[] args) throws exception{        Thread T =new myThread ();        T.start ();        T.interrupt ();        System.out.println ("Mark");}    }

Output:

Mark

......

i=999

Join () method

Specific usage http://www.cnblogs.com/luyu1993/p/7017927.html

Here, look at its source code.

Public final synchronized void join (long Millis)     throws interruptedexception {    long base = System.currenttimemillis ();    Long now = 0;    if (Millis < 0) {            throw new IllegalArgumentException ("Timeout value is negative");    }    if (Millis = = 0) {        while (isAlive ()) {        Wait (0),        }    } else {while        (IsAlive ()) {        Long delay = mil Lis-now;        if (delay <= 0) {break            ;        }        Wait (delay);        now = System.currenttimemillis ()-Base;}}}    

  

Join () calls the wait () Note that the thread must obtain a lock on the object before calling wait (), so the Wait () method can only be called in the synchronous method/synchronous code block . You can see that the join () method is synchronized, so no problem.

Look at the code below.

1 classMyThreadextendsthread{2 @Override3      Public voidrun () {4          for(inti = 0; i < 1000; i++) {5 System.out.println (i);6         }7     }8 }9  Public classWaittest {Ten  One      Public Static voidMain (string[] args)throwsexception{ AThread T =NewMyThread (); - T.start (); - Thread.CurrentThread (). Wait (); theSystem.out.println ("Mark"); -     } -  -}

At this time the program will error not calling the Wait () method in the synchronization method/synchronization code block!!!

Java Multithreading---Wait () & Join ()

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.