Sleep () and yield () methods

Source: Internet
Author: User
Tags thread class

It programmer development must-all kinds of resources download list, the most complete IT resources in history, personal collection summary.

1.sleep ()
Causes the current thread (that is, the thread that calls the method) to suspend execution for a period of time so that other threads have the opportunity to continue executing, but it does not release object locks. That is, if there is a synchronized synchronization block, other threads still have different access to the shared data. Note that this method catches exceptions
For example, there are two threads executing at the same time (no synchronized), one thread priority is max_priority, the other is min_priority, if there is no sleep () method, the lower priority thread can execute only after the high priority thread has finished executing , but when the high priority thread sleep (5000), the lower priority has a chance to execute.
In short, sleep () can give low-priority threads an opportunity to execute, and, of course, give the same priority, high-priority threads an opportunity to execute.
2.join ()
The join () method causes the thread that invoked the method to finish before this, that is, wait until the thread that called the method finishes execution, and then proceed down. Note that the method also catches exceptions.
3.yield ()
It is similar to sleep (), except that the user cannot specify how long the pause is paused, and the yield () method can only give the same priority thread the chance to execute.
4.wait () and notify (), Notifyall ()
These three methods are used to coordinate the access of multiple threads to shared data, so the three methods must be used within the synchronized statement block. Previously said synchronized this keyword is used to protect shared data and prevent other threads from accessing shared data. However, the process of the program is not flexible enough to allow other threads to access the shared data when the current thread has not exited the synchronized data block. Now use these three methods to control the flexibility.
The wait () method causes the current thread to suspend execution and release the object lock flag so that other threads can enter the synchronized data block, and the current thread is placed in the object waiting pool. When the Notify () method is invoked, an arbitrary thread is removed from the waiting pool of the object and placed in the lock flag wait pool, only the lock flag waits for the thread in the pool to get the lock flag, and notify () does not work if the lock flag waits for no threads in the pool.
Notifyall () Removes all threads waiting for that object from the object wait pool and puts it in the lock flag waiting pool.
Note that these three methods are Java.lang.Ojbect methods!

2.run () and start ()
Both methods should be familiar, putting code that requires parallel processing in the run () method, and the start () method starts the thread to automatically invoke the run () method, as defined by the Java memory mechanism. and the run () method must be public access and the return value type is void.
3. Keyword synchronized
This keyword is used to protect shared data, but the prerequisite is to distinguish between which data is shared data. Each object has a lock flag, and when a thread accesses the object, the data decorated by the synchronized is "locked" to prevent other threads from accessing it. When the current thread has finished accessing this part of the data, the lock flag is released and other threads are accessible.

1 2 3 4 5 6 7 8 9-A-list Public ThreadTest implements runnable{     public synchronized void Run () {          for (int i= 0;i< i++) {         & nbsp;   System.out.println ("" + i);         }     }      public static void Main (string[] args) {         Runnable r1 = new ThreadTest ();           Runnable r2 = new ThreadTest ();          thread T1 = new Thread (r1);          thread t2 = new Thread (r2);          T1.start ();          T2.start ();     }       //I variables in this program are not shared data, which means that the Synchronized keyword here does not work. Because t1,t2 two threads are threads of two objects (R1,R2)。 Different objects have different data, so the I variable of the R1 and R2 two objects is not shared data.      when the code is changed to the following: The Synchronized keyword will play a role      Runnable r = new ThreadTest ();      thread T1 = new Thread (r);      thread t2 = new Thread (r);      T1.start ();      T2.start ();

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

(1). The usual wait method has a wait () and a wait (long timeout):
void Wait () results in the current thread waiting before other threads call the Notify () method or Notifyall () method of this object.
void wait (long timeout) causes the current thread to await when other threads call the object's notify () method or Notifyall () method, or before the specified amount of time.
After wait (), the thread frees up its "lock flag" so that other synchronized data in the object where the thread resides can be used by another thread.
Wait () and notify () have to be invoked in the synchronized function or synchronized block because they operate on the lock flags of the objects. If invoked in the Non-synchronized function or in the non-synchronized block, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.

(2). Thread.Sleep (long Millis) must be preceded by a time parameter.
Sleep (long) causes the current thread to stagnate, so the thread that executes the sleep () is certainly not executed within the specified time;
Sleep (long) enables lower-priority threads to execute and, of course, gives the same priority and High-priority threads the opportunity to execute;
Sleep (long) does not release the lock flag.

(3). Yield () has no parameters.
Sleep method so that the current running threads sleepy for a period of time, into a not-running state, the length of time is set by the program, yield method to make the current thread out of the CPU, but the time is not set.
Yield () also does not release lock flags.

In fact, the yield () method corresponds to detecting whether the current thread with the same priority is in the same running state, and if so, handing over the CPU's possession to the thread, or continue running the original thread. So the yield () method is called "concession", which gives the running opportunity to other threads of equal priority.

The Sleep method allows a lower-priority thread to get a chance to run, but when the yield () method executes, the current thread is still in a running state, so it is not possible to give the lower-priority thread some time to gain CPU possession. 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 of the opportunity to run.

Yield () simply brings the current thread back to the executable state, so the thread that executes the yield () is likely to be executed immediately after it enters the executable state. So yield () can only make the same priority thread have an opportunity to execute.

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.