Java 7 Concurrency Cookbook Translation The first chapter of thread management

Source: Internet
Author: User
Tags thread class

V. Sleep and wake up a thread

Sometimes you will want to run the thread after a certain amount of time. For example, a thread in a program checks the state of the sensor every minute, and the remaining time, the thread should be in an idle state. During this idle time, the thread does not use any of the computer's resources. A minute later, the thread is ready to let the JVM choose to invoke it to continue. You can use the sleep () method of the Thread class to achieve this purpose. The method accepts an int type parameter indicating the number of milliseconds that the thread hangs without running. When the sleep time is over, the thread shifts to the operational state to wait for the JVM to dispatch.

A member of the Timeunit enumeration class also has the sleep () method. The method uses the sleep () method of the thread class to make the current thread sleep, but the unit of the parameter it accepts is not fixed to a number of milliseconds and is more convenient.

In this tip, we develop a program that uses the sleep () method to output a Date value per second.

 Public classFilemain { Public Static voidMain (string[] args) {Fileclock clock=NewFileclock (); Thread Thread=NewThread (clock);                Thread.Start (); Try{TimeUnit.SECONDS.sleep (5); } Catch(interruptedexception e) {e.printstacktrace ();    } thread.interrupt (); }} Public classFileclockImplementsrunnable{@Override Public voidrun () { for(inti = 0; I < 10; i++) {System.out.printf ("%s\n",NewDate ()); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {System.out.printf ("The Fileclock has been interrupted"); }        }    }    }

When you call the Sleep () method, the thread discards the CPU and stops executing for a period of time. During this time, it does not consume CPU time.

When the thread is in sleep and is interrupted, the method immediately throws a Interruptedexception exception and does not wait until the sleep time arrives.

NOTE: The yield () method also has the ability to let threads discard CPU usage, but this method is best used only to indicate that it is possible to discard CPU usage, and that the JVM's specification does not require it to abandon CPU usage. This method is typically used only in a debug environment, allowing a thread with higher privileges to preempt execution.

The author concludes: After the thread calls the sleep () method, the thread is in a suspended state and will not be able to preempt resources such as cups, but there is a system thread inside the JVM to sense if the sleep thread is interrupted, so that the sleep thread is thrown in an unusual way to notify the sleeping threads to wake early to run the code to handle this situation.

Six, waiting for the completion of the thread

In some scenarios, we may need to wait for the end of the thread. For example, our programs may need to initialize certain resources before performing certain steps in order. We can run the task of initializing the resource as a separate thread and wait for it to finish in the main task thread before proceeding with the next step.

We can use the join () method of the Thread class to do this. When we call the join () method of a thread object, the thread that calls this method hangs until the thread associated with the threads object finishes executing.

 Public classDatasourcesloaderImplementsrunnable{@Override Public voidrun () {System.out.printf ("Beginning Data Sources loading:%s\n",                 NewDate ()); Try{TimeUnit.SECONDS.sleep (4); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.printf ("Data sources loading has finished:%s\n",                 NewDate ()); }    } Public classMain { Public Static voidMain (string[] args) {Datasourcesloader Dsloader=NewDatasourcesloader (); Thread Thread1=NewThread (Dsloader, "Datasourcethread"); Networkconnectionsloader Ncloader=NewNetworkconnectionsloader (); Thread thread2=NewThread (Ncloader, "Networkconnectionloader");        Thread1.start ();                Thread2.start (); Try{thread1.join ();        Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.printf ("Main:configuration has been loaded:%s\n",NewDate ()); }} Public classNetworkconnectionsloaderImplementsrunnable{@Override Public voidrun () {System.out.printf ("Beginning Network Connection:%s\n",                 NewDate ()); Try{TimeUnit.SECONDS.sleep (4); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.printf ("Network connection has finished:%s\n",                 NewDate ()); }    }

If you run this sample program multiple times, you will find that the main thread will not end until you run the Thread1 and end before running thread2,thread2 ends.

The join () method has two similar methods, respectively:

(A) Join (long milliseconds)

(B) Join (long milliseconds, long Nanos)

These two methods lead to the end of the thread that will suspend the calling thread until the threads object that the method belongs to executes, but after the specified time is reached, the calling thread can continue to run without waiting.

The author concludes: These three methods are often used for synchronization between threads, the method with parameters can be implemented timeout does not wait for the logic.

Important: This series of translation documents will also be in my public number (this mountain is my opening) the first time to publish, welcome attention.

Java 7 Concurrency Cookbook Translation The first chapter of thread management

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.