Java review-thread-related methods introduction

Source: Internet
Author: User

1. Sleep ()

causes the current thread (that is, the thread that called the method) to pause for a period of time so that other threads can continue to execute, but it does not release the object lock (if it is in a synchronized block, He's not going to release the lock. ). This means that if there is a synchronized synchronization block, other threads still cannot access the shared data. Note that the method is a static method, but the system automatically recognizes which thread called the sleep time.

For example, there are two threads executing at the same time (without synchronized) One thread priority is max_priority, the other is min_priority, and if there is no sleep () method, the low-priority line friend can execute when the high-priority thread finishes executing But when the high-priority thread sleep (500), the low priority has a chance to execute.

In summary, sleep () allows a low-priority thread to get the chance to execute and, of course, allow the same priority, high-priority threads to execute.

Note: We all know that the main thread (main) will not exit if all of the child threads have not been executed, but if the child threads are all daemon threads, that is, before the thread start is set to Setdaemon (true); Then the child thread will die. When I was doing the unit test, I found that even though all my child threads were non-daemons, I let him sleep for 1 seconds after the child thread entered, and found that the thread was out after the main thread had finished running, unless I slept longer in the main thread, the program would continue to execute.


2. Join ()

Join () method, when a thread such as Thread1, he calls Thread1.join (); Then the code after the Thread1.join () method must be all code before Thread1.join () and Thread1.run Method execution is complete before execution!

For example there are three threads, thread0,thread1,thread2;

Thread0.start ();

Thread1.start ();

Thread1.join (); call join here, you must wait for thread0 and thread1 to complete before executing thread2

Thread2.start ();


3. Yield ()

This method is similar to sleep (), except that it is not possible for the user to specify how long to pause, and the yield () method only allows the same priority thread to have an opportunity to execute. the same yield will not release the object lock , in fact, the purpose of calling this method is to let the thread from the new competition resources, a display of the notification.


4. Wait () and notify (), Notifyall ( )

These three methods are used to coordinate the access (synchronization) of multiple threads to shared data, so they must be used within the synchronized statement block. the synchronized keyword is used to protect shared data and prevent other threads from accessing the shared data, but the process of the program is inflexible and how can other threads have access to shared data when the current thread has not exited the synchronized data block? At this point, use these three methods to control flexibly.

The wait () method suspends the current thread and releases the object lock, allowing other threads to enter the synchronized data block, where the current thread is placed in the object waiting pool. When the Notify () method is called, an arbitrary thread is removed from the object's wait pool and placed in the lock flag waiting pool, and only the lock flag waits for the thread to acquire the lock flag, and notify () does not work if there are no threads in the lock flag waiting pool.

Notifyall () removes all the threads waiting for that object from the object waiting pool and puts it in the lock flag waiting pool.

Note that these three methods are java.lang.Object methods.



5, run and start ()

Put the code that needs to be processed into the run () method, and the start () method will automatically call the run () method, which is defined by the Java memory mechanism. and the run () method must be public access, and the return value type is void.


6. Keyword synchronized

This keyword is used to protect shared data, but the prerequisite is to distinguish which data is shared. Each object has a lock flag, and when a thread accesses the object, the synchronized-modified data is "locked" and blocked from being accessed by other threads. When the current thread finishes accessing this piece of data, the lock flag is released and other threads can access it.



7. Precautions

Wait () and notify (), Notifyall () are methods of the object class, and sleep () and yield () are methods of the thread class.

(1), the usual wait method has wait () and wait (long timeout);

void Wait () causes the current thread to wait before other threads call the Notify () method of this object or the Notifyall () method.

void wait (long timeout) causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method, or exceeds the specified amount of time.

After wait (), the thread releases the "lock flag" that it occupies, so that other shnchronized data in the object where the thread resides can be used by other threads.


Wait () H and notify () because they operate on the object's "lock flags," they must be called in the synchronized function or synchronized block. If the call is made in the non-synchronized function or non-synchronized block, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.


(2), Thread.Sleep (long Millis) must have a time parameter.

Sleep (long) puts the current thread into a stagnant state, so the thread executing sleep () will not be executed for a specified period of time;

Sleep (long) allows the thread with the lower priority to be executed and, of course, the opportunity to execute with the same priority thread;

Sleep (long) does not release the lock flag.


(3), yield () No parameters

The Sleep method causes the currently running thread to be asleep for a period of time, entering the non-operational state, the length of time is set by the program, and the yield method allows the current thread to give up the CPU possession, but the time to make up is not settable.

Yield () also does not release the lock flag.

In fact, the yield () method corresponds to the following operations, first detect whether there is currently the same priority of the thread is in the same operational state, if so, the CPU's possession to the secondary thread, or continue to run the original thread, so the yield () method is called "concession", It gives the running opportunity to other threads of the same level.


The Sleep method allows a lower-priority thread to get a run opportunity, but when the yield () method executes, the current thread is still in a running state, so it is not possible to let the lower-priority thread get CPU possession at this time. In a running system, if a higher-priority thread does not call the sleep method and is not blocked by I/O, the lower-priority thread can only wait for all higher-priority threads to run to the end before the opportunity runs.


Yield () simply returns the current thread back to the executable state, and all threads that execute yield () are likely to be executed immediately after entering the executable state, so the yield () method only allows the same priority thread to have an opportunity to execute.





Java review-thread-related methods introduction

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.