Java multithreading technology-wait/notify/join,-waitpolicy

Source: Internet
Author: User

Java multithreading technology-wait/notify/join,-waitpolicy
Functions of wait/notify

The wait () method is used to wait for the thread executing the code. The wait () method is an Object class method to put the current thread into the pre-execution queue and () the execution of the Code stops until it is notified or interrupted. Before calling wait (), you must obtain the object-Level Lock of the object. That is, you can only call the wait () method in the synchronous method or synchronous code block. Otherwise, an IllegalMonitorStateException is thrown. When wait () is executed, the current thread releases the lock

The notify () method is used to notify other threads that may wait for the object lock of the object. If there are multiple threads waiting, a thread in the wait state is randomly selected, send a notification to it and wait for it to get the object lock of the object. Before calling notify (), you must obtain the object-Level Lock of the object. That is, you can only call the notify () method in the synchronous method or synchronous code block. Otherwise, an IllegalMonitorStateException is thrown. When the notify () method is executed, the lock of the object will not be immediately released, and the thread in the wait status cannot immediately obtain the lock of the object. wait until the notify () method is executed () the current thread releases the lock after the program is executed, that is, the synchronized code block is exited.

The yyall () method and notify () method have the same functions. One is to wake up all the wait threads, and the other is to wake up one of the wait threads.

Typical Case producer and consumer

Public class MyStack {private List <String> list = new ArrayList <> (); public synchronized void push () {try {while (list. size () = 1) {System. out. println ("push:" + Thread. currentThread (). getName () + "wait status"); this. wait ();} list. add ("anyString =" + Math. random (); this. policyall (); System. out. println ("push =" + list. size ();} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public synchronized String pop () {String returnValue = ""; try {while (list. size () = 0) {System. out. println ("pop:" + Thread. currentThread (). getName () + "wait status"); this. wait ();} returnValue = list. get (0); list. remove (0); this. policyall (); System. out. println ("pop =" + list. size ();} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}return returnValue ;}} public class Product {private MyStack myStack; public Product (MyStack myStack) {this. myStack = myStack;} public void pushService () {myStack. push () ;}} public class Customer {private MyStack myStack; public Customer (MyStack myStack) {this. myStack = myStack;} public void popService () {myStack. pop () ;}} public class ThreadCustomer extends Thread {private Customer customer Customer; public ThreadCustomer (customer Customer) {this. customer = customer ;}@ Override public void run () {while (true) {customer. popService () ;}} public class ThreadProduct extends Thread {private Product product; public ThreadProduct (Product product Product) {this. product = product ;}@ Override public void run () {while (true) {product. pushService () ;}} public class Test {public static void main (String [] args) throws InterruptedException {MyStack myStack = new MyStack (); product p = new Product (myStack); Customer c = new Customer (myStack); ThreadProduct pThread = new ThreadProduct (p); ThreadCustomer cThread = new ThreadCustomer (c); pThread. start (); cThread. start ();}}
View Code

 

Function of join

Join () is a method of the Thread class. It enables the Thread x object to normally execute tasks in the run method, and causes the current Thread z to block indefinitely, wait until thread x is destroyed before executing the code after thread z.

Public class MyThread extends Thread {@ Override public void run () {try {System. out. println (System. currentTimeMillis (); Thread. sleep (3000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public class Test {public static void main (String [] args) throws InterruptedException {MyThread myThread = new MyThread (); myThread. start (); myThread. join (); System. out. println ("output after myThread execution:" + System. currentTimeMillis ());}}
View Code

Test results:

1516170164683 output after myThread execution: 1516170167686
Difference between join and synchronized

From the above example, we can see that the join method plays a role in thread queuing, and some classes are the synchronous running effect. The difference between join and synchronized is that join uses the wait () method internally to wait, while synchronized uses the "Object monitor" principle for synchronization.

Difference between join (long) and sleep (long)

Since the join is implemented using wait internally, it has the feature of releasing the lock, and sleep does not.

The source code is as follows:

 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 = millis - now;                if (delay <= 0) {                    break;                }                wait(delay);                now = System.currentTimeMillis() - base;            }        }    }

 

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.