Program to demonstrate how to put a thread to sleep in Java using yield and sleep method
package com.hubberspot.multithreading; public class ProducerConsumerTest { public static void main(String[] args) { // 3. Create a thread by instantiating // an object from the class Thread producer = new Producer(); Thread consumer = new Consumer(); // 4. Call the start() method of the // thread object producer.start(); consumer.start(); // Overall three threads are created // 1. for main method , 2. for the Producer class // 3. for the Consumer class } } // 1. Create a class that extends Thread class Producer extends Thread { // 2. Overload the run method to perform // the desired task public void run(){ for (int i = 0; i < 10; i++){ System.out.println("I am Producer : Produced Apple " + i); // 1. one way to put thread to sleep // static method that pause current thread so that other thread // gets the time to execute Thread.yield(); try { // 2. another way to thread to sleep // It takes an argument of int which // specifies time in milliseconds for // pausing or making a thread sleep. // Generally, thread goes to blocked state // for the time specified... here its 1 second Thread.sleep(1000); // Thread.sleep() method throws Interrupted Exception // if something interrupts the thread on sleeping } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer extends Thread { public void run(){ for (int i = 0; i < 10; i++){ System.out.println("I am Consumer : Consumed Apple " + i); Thread.yield(); try { // 2. another way to thread to sleep // It takes an argument of int which // specifies time in milliseconds for // pausing or making a thread sleep. // Generally, thread goes to blocked state // for the time specified... here its 2 seconds Thread.sleep(2000); // Thread.sleep() method throws Interrupted Exception // if something interrupts the thread on sleeping } catch (InterruptedException e) { e.printStackTrace(); } } } }Output of the program :