Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Concurrency Cookbook, Second Edition

You're reading from   Java 9 Concurrency Cookbook, Second Edition Build highly scalable, robust, and concurrent applications

Arrow left icon
Product type Paperback
Published in Apr 2017
Publisher Packt
ISBN-13 9781787124417
Length 594 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Javier Fernández González Javier Fernández González
Author Profile Icon Javier Fernández González
Javier Fernández González
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Thread Management FREE CHAPTER 2. Basic Thread Synchronization 3. Thread Synchronization Utilities 4. Thread Executors 5. Fork/Join Framework 6. Parallel and Reactive Streams 7. Concurrent Collections 8. Customizing Concurrency Classes 9. Testing Concurrent Applications 10. Additional Information 11. Concurrent Programming Design

Sleeping and resuming a thread

Sometimes, you may be interested in pausing the execution of a thread during a determined period of time. For example, a thread in a program checks the sensor state once per minute. The rest of the time, it does nothing. During this time, the thread doesn't use any resources of the computer. After this period is over, the thread will be ready to continue with its execution when the operating system scheduler chooses it to be executed. You can use the sleep() method of the Thread class for this purpose. This method receives a long number as a parameter that indicates the number of milliseconds during which the thread will suspend its execution. After that time, the thread continues with its execution in the next instruction to the sleep() one when the JVM assigns it CPU time.

Another possibility is to use the sleep() method of an element of the TimeUnit enumeration. This method uses the sleep() method of the Thread class to put the current thread to sleep, but it receives the parameter in the unit that it represents and converts it into milliseconds.

In this recipe, we will develop a program that uses the sleep() method to write the actual date every second.

Getting ready

The example for this recipe has been implemented using the Eclipse IDE. If you use Eclipse or a different IDE, such as NetBeans, open it and create a new Java project.

How to do it...

Follow these steps to implement the example:

  1. Create a class called ConsoleClock and specify that it implements the Runnable interface:
        public class ConsoleClock implements Runnable {
  1. Implement the run() method:
        @Override 
public void run() {
  1. Write a loop with 10 iterations. In each iteration, create a Date object, write it to the console, and call the sleep() method of the SECONDS attribute of the TimeUnit class to suspend the execution of the thread for 1 second. With this value, the thread will be sleeping for approximately 1 second. As the sleep() method can throw an InterruptedException exception, we have to include some code to catch it. It's good practice to include code that frees or closes the resources the thread is using when it's interrupted:
          for (int i = 0; i < 10; i++) { 
System.out.printf("%s\n", new Date());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.printf("The FileClock has been interrupted");
}
}
}
  1. We have implemented the thread. Now let's implement the main class of the example. Create a class called Main that contains the main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create an object of the FileClock class and a thread to execute it. Then, start executing a thread:
        FileClock clock=new FileClock(); 
Thread thread=new Thread(clock);
thread.start();
  1. Call the sleep() method of the SECONDS attribute of the TimeUnit class in the main thread to wait for 5 seconds:
        try { 
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
};
  1. Interrupt the FileClock thread:
        thread.interrupt();
  1. Run the example and see the results.

How it works...

When you run the example, you would see how the program writes a Date object per second and also the message indicating that the FileClock thread has been interrupted.

When you call the sleep() method, the thread leaves the CPU and stops its execution for a period of time. During this time, it's not consuming CPU time, so the CPU could be executing other tasks.

When the thread is sleeping and is interrupted, the method throws an InterruptedException exception immediately and doesn't wait until the sleeping time is finished.

There's more...

The Java concurrency API has another method that makes a thread object leave the CPU. It's the yield() method, which indicates to the JVM that the thread object can leave the CPU for other tasks. The JVM does not guarantee that it will comply with this request. Normally, it's only used for debugging purposes.

You have been reading a chapter from
Java 9 Concurrency Cookbook, Second Edition - Second Edition
Published in: Apr 2017
Publisher: Packt
ISBN-13: 9781787124417
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime