Waiting and waking in a thread

Source: Internet
Author: User

When the previous article talked about the join () method, a function was used as the yield () method, which was used to make the cup available to threads with the same priority. This article will tell you about the functions of waiting and waking in threads.

Sleep ():

Suspends the current thread for a period of time so that other threads continue to have the opportunity to execute, but it does not release object locks, that is, when there is a synchronized keyword, other threads still cannot access their shared resources. The sleep () method requires the user to set the blocking time. When the user sets the Sleep () method, the thread must not be executed, so the lower priority thread will have the opportunity to execute. That is, if a high-priority thread does not have sleep () or I/O blocking, the low-priority thread can only wait, and it will only be able to execute if the higher-priority thread finishes executing.

Yield ():

This method has the same function as the sleep () method, except that the time of the method is not set by ourselves, but by the system, and it only gives the same priority thread the opportunity to execute first. That is, executing the Yeld () method, this thread will look for a thread that has the same priority as it does, and if so, let the thread with the same priority be executed. If it does not, it returns to continue executing the original thread. So the yield () method can only give the same priority thread the opportunity to execute, without giving the low-priority thread a chance. (Don't let others stay alive.)

The specific code examples are as follows:

When the package sleepandwait;/** * calls the Sleep () method, we can specify the time that the thread needs to rest by itself, and when the yield () method is called, we don't know how long the thread needs to rest, and * yield () The method is to have the same priority thread execute first. * @author Administrator * */public class Test {public static void main (string[] args) {Thread T1 = new Thread (New Myrunnab Le (+)); t1.setpriority (9); T1.start (); Thread t2 = new Thread (new myrunnable); t2.setpriority (6); T2.start (); thread t3 = new Thread (new myrunnable); t3.setpriority (9); T3.start ();}} Class Myrunnable implements Runnable{private int time;public myrunnable (int time) {this.time = time;} @Overridepublic void Run () {try {thread.sleep (time);} catch (Interruptedexception e) {e.printstacktrace ();} Thread.yield ();//system.out.println ("I am Thread:"//+thread.currentthread (). GetName () +//"I'm calling the yield () method, how long I've been blocked I don't know ..."); System.out.println ("I am Thread:" +thread.currentthread (). GetName () + "I was blocked" +time+ "seconds!");}

When we comment out the sleep () method and replace it with the wait () method, we see that T1 and T3 are executed first, and finally T2.

Note: both sleep () and yield () simply pause the execution of the current thread and do not give up shared resources.

Wait (), notify (), Notifyall ():

Wait (), notify (), Notifyall () are used to coordinate the access of multiple threads to shared data, so they must be used in the synchronized statement block. The Synchronized keyword is used to protect shared resources and prevent other threads from accessing shared resources, but this makes the program very inflexible. How can the current thread not exit synchronized, allowing other threads to access the shared resource, three ways to make your program flexible

The wait () method causes the current thread to pause execution and release the object lock flag, let other threads enter the synchronized data block, the current thread is put into the object waiting pool, and when the Notify () method is called, any one of the threads will be moved back to the lock flag waiting pool. The Notifyall () method removes all the threads waiting for that object from the object waiting pool and puts it in the lock flag waiting pool.

Notify (): Wakes a single thread on this object monitor.

Notifyall (): Wakes all threads on this object monitor.

Wait (): keeps the current thread in a blocking state until the other thread calls the Notify () or Notifyall () method of this object, and the current thread is awakened.

Wait (long timeout): keeps the current thread in a blocking state until the other thread calls the Notify () or Notifyall () method of the object, or exceeds the specified amount of time to wait for the current thread to wake.

The Notify () test code is as follows:

Package Sleepandwait;public class MyThread extends Thread{public MyThread (String name) {super (name);} public void Run () {synchronized (this) {System.out.println (Thread.CurrentThread (). GetName () + "Waiting to wake up ..."); System.out.println ("I am a Thread" +thread.currentthread (). GetName () + ": I am called notify!"); /wakes the current thread's wait () waits for Notify ();}}}
Package Sleepandwait;public class Testnotify {public static void main (string[] args) {MyThread T1 = new MyThread ("T1 thread"); s ynchronized (t1) {try{system.out.println (Thread.CurrentThread (). GetName () + "start ..."); T1.start (); System.out.println (Thread.CurrentThread (). GetName () + "wait!"); /T1 thread enters the wait state t1.wait (); System.out.println (Thread.CurrentThread (). GetName () + "continue ..."); catch (Exception e) {e.printstacktrace ();}}}}
Notifyall () test code:

Package Sleepandwait;public class Testnotifyall {private static object obj = new Object ();p ublic static void Main (string[] args) {Thread T1 = new Threada ("T1"); Thread t2 = new Threada ("T2"); Thread t3 = new Threada ("T3"); T1.start (); T2.start (); T3.start (); try {System.out.println (Thread.CurrentThread (). GetName () + "sleep3000"); Thread.Sleep (3000);} catch (Interruptedexception e) {e.printstacktrace ();} Synchronized (obj) {///main thread waits for Wake System.out.println (Thread.CurrentThread (). GetName () + "notifyall."); O Bj.notifyall ();}} Static class Threada extends Thread{public Threada (String name) {super (name);} public void Run () {synchronized (obj) {try{system.out.println (Thread.CurrentThread (). GetName () + "wait!"); /wakes the current thread's wait obj.wait (); System.out.println (Thread.CurrentThread (). GetName () + "continue!");} catch (Interruptedexception e) {e.printstacktrace ();}}}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Waiting and waking in a thread

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.