Program to demonstrate creation of a thread by extending the Thread class in Java
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);
// static method that pause current thread so that other thread
// gets the time to execute
Thread.yield();
}
}
}
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();
}
}
}
Output of the program : 