Thursday, November 22, 2018
Home > java > Multithreading in Java

Multithreading in Java

Multithreading in Java

Multithreading in Java is a really important topic. Today we are going to discuss complete multithreading with the help of some example which is described the flow of multithreading. The basic aim of Multithreading is to develop concurrent execution based on application.
(Simultaneous/parallel execution of multiple logic represented in the method is called concurrent execution.)

“A flow of control is known as the thread.”

The purpose of the thread is to execute a logic of the Java program which written in the form of user methods. If a Java program containing multiple flows of control then it is called multithreaded.

Language like C/C++ are come under single-threaded modeling language because their execution environment provided a single flow of control, provide sequentially execution, take more execution time and not containing any library for development of trade based application.

The languages like Java and .net come under multithread modeling language because their execution provides multiple flows of control, provide concurrent execution, take less execution time and containing an effective API for development of thread based application.

To develop multithreading in Java we have two API.

1) java.lang.Thread (class)
2) java.lang.Runnable (Interface)

Types of threads in java


Whenever you write a Java Program, there exist two types of thread they are

1) Foreground/child thread
2) Background/parent thread

A Foreground thread is one which will always execute the logic of the Java program which is written in the form of a user-defined method.
background thread is one which is monitoring the execution status of foreground threads.

By default there exist single foreground and single background thread.
Programmatically there exist multiple foreground threads and recommended to have a single background thread.

The real-time integration of multiple threading is to develop Real-world server software(Tomcat, Weblogic). In other words, most of the third-party software vendors developed their server software by making use of the multithreading concept. Hence multithreading of Java is one of the specified forms of multitasking of operating System.


How do you justify Java is one of the multithreaded programming languages?
When we executed any Java program the logic of the Java program is executed by one of the thread known as Foreground thread. Internally to monitor the execution status of foreground thread, there exists one more thread known as a background thread. So every Java program is containing multiple threads hence every Java program is multithread.

What are the differences between program and process


Program

Process

1) A program is a set of optimized instruction.1) A program is under execution is called process.
2) A program always stores in secondary memory for a long time.2) Process main memory for a limited period of time.
3) A program is considered as a static object.3) A process is considered as a dynamic object.

What are the differences between process-based/Non- multitasking application and thread-based/multitasking application


Process-based application(PBA)

Thread-based application(TBA)

1) In PBA there exists a single flow of control.1) In TBA, there exist multiple flows of control.
2) All the application of single-threaded modeling language is coming under PBA.2) all the applications of multithreading modeling language are coming under TBA.
3) PBA Takes more execution time.3) TBA take less execution time.
4) In PBA, Context switching is more.4) In TBA, context is switch less.
5) In PBA, For each and every subprogram there exist a separate address space.5) In TBA, irrespective of the number of subprograms there exist single address space.
6) PBA Always provide only sequential education and unable to provide concurrent execution.6) TBA provide both sequential and concurrent execution.
7) all PBA are treated as a heavyweight component.7) All the TBA are treated as light weight component.

Address space: It is the amount of temporary memory space created by the operating system on stack memory for execution of the method.

Context switch: The mechanism of switching the control of the CPU from one address space to another address space is known as the context switch.

Note: A heavyweight component is one whose processing time is more whereas a lightweight component is one whose processing time is less.

Note: Each and every thread based application is one of the process based application in which one main process created by the operating system and the main process create sub process. In Java programming point of view, the main process is called thread group name or the subprocess is called foreground thread. The following diagram will describe the thread.

Foreground thread and backkground thread

But a process-based application during its execution time it will be considered as a Process-based application only because they exist only one process. The following diagram described the flow in the process based application.

life cycle of Multithreading in Java


The number of state occurring in the execution of the logic of a Java Program by the thread is called the life cycle of a thread.

The states of thread are classified into 5 types.

Life cycle state
1) new state
2) ready state
3) running state
4) waiting state
5) Halted state

Thread Life Cycle

New state: In New state, the thread is created and it is the above to enter into the main memory.

Ready state: In ready state thread is enter into main memory, memory space is allocated for the thread and first time waiting for the CPU.

Running state: In running state that thread is under the control of CPU or a thread is said to be in running state if and only if the thread is under execution.

Halted state: In this state, the thread is completed its total execution or completed its total CPU burst time by the CPU.

CPU burst time: The amount of time required by the thread from the device CPU is called CPU burst time. it is decided by the operating system

Waiting state:
A thread is said to in waiting state if and only if any of the following condition satisfied by the thread.

Waiting state condition
1) The thread is coming to waiting for a state for the remaining CPU burst time.
2) making the currently executing thread to sleep for some period of time(in millisecond 1second=1000ms)
3) making the currently executing thread to suspend. or making the currently executing thread to wait with time.
4) Making the currently executing thread to wait without time.
5) making the currently executing thread to join.

Hence in the life cycle of thread new state and halted state are called out memory state and whose execution status is false. Whereas ready state, running state and waiting state are called in-memory state and whose execution status is true. And in the JAVA thread program environment, the threads which are present in the Java program are executed concurrently with the difference of millisecond of time by following Round Robin algorithm.

Creating a thread


We know that the purpose of thread is executing logic of Java program which is written in the form of user defined method. In Java programming we have two approaches to create a thread.
1) by using java.lang.Thread class.
2) by using java.lang.Runnable Interface.

By using java.lang.Thread class.


Creating a flow of control is nothing but creating an object of java.lang.Thread. An object of java.lang.Thread class can be created in three ways.
1) by using “new” operator
Thread t1=new Thread();
2) by using a factory method
Thread t2=Thread.cutrrentThread();
3) by creating an object of a subclass of java.lang.The thread is indirectly an object of java.lang.Thread class.

class Th3 extends Thread 
{ 
  ------------ 
  ----------- 
} 
Th3 t3=new Th3();

“t3” is an object of “Th3” and it is a subclass of java.lang.Thread.

Profile of java.lang.Thread class


Data members


1) Public static final int MAX_PRIORITY(=10)
2) Public static final int NORM_PRIORITY(=5)
3) Public static final int MIN_PRIORITY(=1)

The above data members are called thread priority modifiers.
Thread priority modifiers makes the CPU to understand which thread to execute first, which thread to execute second and last. The default priority of the thread is NORM_PRIORITY(=5)

Constructors


Thread()

This constructor is used for creating an object of thread class without giving user defined name of the thread.

Thread t=new Thread(); 
Default name assign by JVM: Thread-0

Thread(String)

This constructor is used for creating an object of thread class by giving user defined name of the thread.

Thread t=new Thread("T4Tution"); //User-Friendly name

Thread(Runnable)

This constructor is used for converting runnable interface object into thread class object for making use of all the method of thread class especially start() method to entering to the overridden run() in the subclass of runnable interface.

Th1 t1=new Th1(); 
or,
Runnable t1=new Th1(); 
t1.start(); //Invalid
Thread t11=new Thread(t1); 
t11.start(); //valid

Thread(Runnable,String)

The functionality of this thread is exactly similar to the above constructor but with this constructor additionally, we are giving user-defined name to the thread.

Th1 t1=new Th1(); 
or,
Runnable t1=new Th1(); 
t1.setName("t4tution"); //Invalid
Thread t11=new Thread(t1,"t4tution"); //valid
t11.getName();//T4tution

Instance methods


1) public final void setName(String);
2) public final String getName();
The above methods are used for setting the user-friendly name to the thread and getting the name of the thread.

Thread t1=new Thread(); //Default name 
t1.setName("T4tution"); //user-friendly name
String tname=t1.getName(); //T4tution

3) public final void setPriority(int)
4) Public final void getPriority()
The above methods are used for setting the priority value to the thread and obtaining the priority value of the thread.

Thread t1= new Thread("T4TUTION"); 
int pv=t1.getPriority(); //default=(5=NORM_PRIORITY) 
t1.setPriority(Thread.MAX_PRIORITY); 
pv=t1.getPriority(); //10= MAX_PRIORITY

5) Public Finance boolean is alive()
A method is used for checking the execution status of a thread, this method returns true if the thread is in IN_MEMMORY states(ready, running, waiting) and it returns False when the thread is in OUT_MEMORY state (new, halted).

6) public final void start()

When we can start() upon the thread class object the internally start() will perform the following operation.
1) it makes the trade to move from a new state to radius state.
2) I provide services to multithreading(concurrency, synchronization, inter-thread communication etc)
3) it automatically calls run() where it contains the logic of the thread.

Th1 t1=new Th1(); //New state 
boolean b1=t1.isAlive(); 
System.out.println(b1); //false 
t1.start(); //ready state 
b1=t1.isAlive(); 
System.out.println(b1); //true

Once the thread is entered into a run() then it is in running state.
Conclusion: Hence to develop a thread based application we always create an object of a subclass of Java.lang.Thread.

7) public final void suspend()
This method is used for suspending the currently executing thread. When we call to suspend() upon the thread class object, the execution of the thread will be stoped, JVM stored the temporary execution detail into PCB(process control block) and send to waiting state.

t1.suspend();

8) public final void resume()
This method is used for transferring the suspended thread from waiting state to ready state.

t1.resume();

Note: When the thread is resumed the JVM start its execution where it left before its suspension by retrieving the temporary execution details from PCB(it is a buffer created by the operating system will the thread is entered first time into ready state and it is meant for storing temporary execution details).

9) public final void stop()
This method is used for terminating or stopping the currently executing thread.When the thread stops its execution, its entered into the halted state. if the stop thread started execution again then they start executing from the beginning.

10) public final void join() throws java.lang.InterruptedException
This method is used for joining the threads as a single unit and handover all the thread at a time to the garbage collector for effective memory management. The default environment of multithreading says collecting the completed thread individually and handover to the garbage collector individually this approach leads to the time-consuming process. It is highly recommended to the Java programmer to join multiple threads as a single unit for improving the performance of thread based application.

This method throws a predefined exception called java.lang.InterruptedException and it is one of the checked exceptions and it must be placed always within try and catch block. This exception always occurs in the client-server environment it never occurred in a stand-alone machine.

Let’s assume there exists “n” number of thread created, started their execution and “n-1” are completed their execution and join together but “nth” thread is under execution due to the mis-memory management of the server-side operating system, the thread group name is attempting to collect “nth” thread which is under execution. At this point of time with respect to “nth” thread JVM generates a pre-defined exception called java.lang.InterruptedException.

------------ 
------------ 
try 
{ 
  t1.join(); 
  t2.join(); 
  --------- 
  --------- 
  tn.join();
} 
catch(InterruptedException ie) 
{ 
  System.err.println("Problem in thread Exception"); 
}

11) public static final int activeCount()
This method is used for finding the number of active threads.

int at=thread.activeCount(); 
System.out.println(at);

12) public static final Thread courrentThread()
It is one of the factory method used for obtaining the thread which is by default running in Java environment.

Thread t=Thread.currentThread(); 
System.out.println(t); //[main,5,main]==[FGT,Priority,BGT] 
t.setName("T4tution"); 
System.out.println(t); //[T4Tution,5,main]

In above example FGT=Foreground Thread and BGT=Background Thread

13)public static final void sleep(long) throws InterruptedException
This method is used for making the currently executing thread to sleep for a period of time in the form of a millisecond of time. When the thread is sleeping it never perform any further operation.when the sleep time is completed automatically the thread will enter into ready and running state from waiting state.
This method throws a pre-defined exception called java.lang.InterruptedException.

InterruptedException does not occur in a standalone application and rarely occurred in the client-server application.
Example: Let us assume the first program threads are sleeping in some location of the server-side operating system. Second program thread attempting to sleep on the same location where first program Threads are sleeping due to the mis-memory management of the server-side operating system at this point of time with respect to first program threads JVM generates a pre-defined exception called java.lang.InterruptedException and it is one of the Checked Exception.

--------------- 
--------------- 
try 
{ 
  ------------- 
  ------------- 
  Thread.sleep(1000); //1 second 
} 
catch(InterruptedException ie) 
{ 
  System.err.println("Problem in thread Exception"); 
}

Write a java program which describes the concept of Thread.


Thread.java

import java.lang.Thread;
public class Main 
{
  public static void main(String[] args) 
  {
    Thread t1=Thread.currentThread();
    System.out.println("Default Name:"+t1); //Thread[main,5,main]
    t1.setName("T4Tution");
    System.out.println("User-defined Name:"+t1); //Thread[T4Tution,5,main]
    System.out.println("Execute Status:"+t1.isAlive()); //true
    Thread t2=new Thread(); //FGT (ForeGround Thread)
    System.out.println("Default Name of FGT: "+t2.getName()); //Thread-0
    System.out.println("Execute Status:"+t2.isAlive());//false
    System.out.println("Value of MAX_Priority:"+Thread.MAX_PRIORITY); //10
    System.out.println("Value of NORM_Priority:"+Thread.NORM_PRIORITY); //5
    System.out.println("Value of MIN_Priority:"+Thread.MIN_PRIORITY); //1
  }
}

OUTPUT

Default Name:Thread[main,5,main]
User-defined Name:Thread[T4Tution,5,main]
Execute Status:true
Default Name of FGT: Thread-0
Execute Status:false
Value of MAX_Priority:10
Value of NORM_Priority:5
Value of MIN_Priority:1

Internal flow of Thread


When we execute the thread based application, the threads of the program will internally execute by following the sequence of steps.

1) java program starts executing.
2) JVM create thread group name(it was stored in main() method). Thread group name create foreground threads.
3) Foreground threads meant for executing the run() method.
4) thread group name dispatch the foreground thread to execute respective Run method.
5) Foreground thread executes respective run() and gives the result to Thread groupname either one by one or once.
6) Threadgroup name receives the result from foreground thread either one by one or at once.
7) Threadgroup name uses the result of java program either one by one or at once.
8) Threadgroup name collects the foreground thread and handover to garbage collector either one by one or at once.
9) JVM collects ThreadGroup name and handover to the garbage collector.
10) java program stops executing.

Write a thread based application which print 1-10 number after each and every second.


Thread_Example2.java

class Th1 extends Thread
{
  public void run()
  {
   try
   {
    for(int i=1;i<=10;i++)
    {
     System.out.println("Value of i:"+i);
     sleep(1000); //Sleep for 1 second
    }
   }
   catch(InterruptedException ie)
   {
    System.err.println("Problem in thread execution");
   }
  }
}
public class Thread_Example2
{
  public static void main(String[] args) 
  {
   Th1 t1=new Th1();
   System.out.println("Execution status of t1 before start:"+t1.isAlive());
   t1.start();
   System.out.println("Execution status of t1 after start:"+t1.isAlive());
   try
   {
    t1.join();
   }
   catch(InterruptedException ie)
   {
    System.err.println("Problem in thread execution");
   }
   System.out.println("Execution status of t1 after completion:"+t1.isAlive());
  }
}

OUTPUT

Execution status of t1 before start:false
Execution status of t1 after start:true
Value of i:1
Value of i:2
Value of i:3
Value of i:4
Value of i:5
Value of i:6
Value of i:7
Value of i:8
Value of i:9
Value of i:10
Execution status of t1 after completion:false

By using jav.lang.Runnable Interface


Runnable is one the pre-defined interface which is used for developing multithreading application. This interface contain following abstract method.

public abstract void run(): This method is used for defining the logic of thread.
To provide the logic of the thread to the run() method of Runnable interface, We must override run() method of Ruunable interface within derived class. Example:

class Th implements Runnable 
{ 
 public void run() 
 { 
   //Logic of Thread
 } 
} 
Th t=new Th(); //Invalid 
Runnable t1=new Th(); 
t1.start(); //invalid 

Because the start() method niether defined in Th nor its inherited from Runnable interface, hence it is mandatory to the java programmer to convert an object of Runnable interface to Thread class object for making use of Thread class all the methods (specially start() method) to enter into run() method of Runnable Interface. 

Write a java program which print 1-10 after each and every second by making use of Runnable Interface.


Runnable_Interface.java

class Th implements Runnable
{
 public void run()
 {
  for(int i=1;i<=10;i++ )
  {
   try 
   {
    System.out.println("Value of i:"+i);
    Thread.sleep(1000);
   }
   catch(InterruptedException ie)
   {
    System.err.println("Problem is in Thread");
   }
  }
 }
}
public class Runnable_Interface 
{
 public static void main(String[] args) 
 {
  Th t =new Th();
  Thread t1=new Thread(t,"DemoTh");
  System.out.println("Name of t1:"+t1.getName()); //DemoTh
  System.out.println("Status of t1:"+t1.isAlive()); //false
  t1.start();
  System.out.println("Status of t1 after start:"+t1.isAlive());//true
 }
}

OUTPUT

Name of t1:DemoTh
Status of t1:false
Status of t1 after start:true
Value of i:1
Value of i:2
Value of i:3
Value of i:4
Value of i:5
Value of i:6
Value of i:7
Value of i:8
Value of i:9
Value of i:10

In Software industry ,you come across N number of independent  task.To solve these task concurrently ,It is mandatory to java programmer to write N number of subclass of overriding N number of run() method by inheriting from either java.lang.Thread class or java.lang.Runnable interface. Each run() method contain a separate logic to solve specific requirement.

Write a java program which will exceute multiple Thread in which one will do ADDITION and other will do SUBTRACTION.


Multiple_Thread.java

class Thread_Add extends Thread
{
 int a,b;
 void set(int a, int b)
 {
  this.a=a;
  this.b=b;
 }
 public void run()
 {
  int add;
  add=a+b;
  System.out.println("ADD:"+add);
 }
}
class Thread_Sub implements Runnable
{
 int a,b;
 void set(int a, int b)
 {
  this.a=a;
  this.b=b;
 }
 public void run()
 {
  int sub;
  sub=a-b;
  System.out.println("SUB:"+sub);
 }
}
public class Multiple_Thread 
{
 public static void main(String[] args)
 {
  Thread_Add add=new Thread_Add();
  Thread_Sub sub=new Thread_Sub();
  Thread tSub=new Thread(sub);
  add.set(12, 6);
  add.start();
  sub.set(15, 5);
  tSub.start();
  try
  {
   add.join();
   tSub.join();
  }
  catch(InterruptedException ie)
  {
   System.err.println("Problem in Thread Execution");
  }
 }
}

OUTPUT

ADD:18
SUB:10

Thread Synchronization in Java


The process of allowing one thread among multiple threads into the shareable area/Resource for performing read and write operation for obtaining a consistent result by eliminating inconsistent result.

Need for synchronization with an example:


Let us assume there is a variable balance with initial value 0 and there exist two Threads t1 and t2 and decided to deposit 10 and 20 in the balance of account concurrently.

Let us assume both the thread started their execution, completed their execution and the final result of balance or value is either 10 or 20 but not 30 which is one of the inconsistent results, Hence to avoid the above inconsistent result you must apply synchronization concept.

Let us assume on the above problem synchronization is and both the thread t1 and t2 execution (t1 start first and t2 starts later with the difference of millisecond of time). JVM gives valuer balance 0 to t1, meanwhile, thread t2 is also attempting to access balance value and JVM makes thread t2 to wait until t1 complete its execution. Thread t1 completed its execution, balance variable Be unlocked, balance variable value becomes 0 to 10, now balance variable is given to t2 and JVM locks balance variable. Thread t2 completed its execution, balance variable becomes 30 which is one of the consistent results.

Conclusion:
Hence, In the synchronize process the process of locking and unlocking will continue until all the threads completed their execution.

Thread synchronization techniques


There are two types of synchronization methods
1) synchronized instance method
2) synchronized static method

synchronized instance method:


If an ordinary instance method access by multiple threads then we get an inconsistent result. To avoid these inconsistent result the declaration of ordinary instance method must be made as synchronized by using thread synchronized keyword.

Syntax

synchronized return_type(parameters)
{
  Block of Statement
}

Once a thread is executing synchronized instance method then JVM will lock an object of the Corresponding class.

Example:

class Account 
{ 
 int balance=0; 
 synchronized void deposit(int amount) 
 { 
  balance=balance+amount; 
  System.out.println("Current Balance:"+balance)
 }
}

When the thread is executing the above-synchronized instance deposit() method then JVM will lock an object of Account class.

synchronized static method:


If an ordinary static method is accessed by multiple threads then we get an inconsistent result. To avoid this inconsistent result, the declaration of the ordinary static method must be made as synchronized by using synchronized.

Syntax

synchronized static return_type(parameters)
{
  Block of Statement
}

Once a thread is executing synchronized static method then JVM will lock an object of the Corresponding class.

Example:

class Account 
{ 
 int balance=0; 
 synchronized static void deposit(int amount) 
 { 
   balance=balance+amount; 
   System.out.println("Current Balance:"+balance)
 }
}

When the thread is executing the above-synchronized static deposit() method then JVM will lock an object of Account class.

Write the java program which illustrates the concept of synchronization.


package com.ravi.java;

class Account
{
private int balance=0;
synchronized void deposit(int amount)
{
balance=balance+amount;
System.out.println("Current Balance:"+balance);
}
int getBalance()
{
return balance;
}
}
class Customer extends Thread
{
Account ac;
Customer(Account ac)
{
this.ac=ac;
}
public void run()
{
ac.deposit(10);
}
}
public class Thread_Synchronization
{
public static void main(String[] args)
{
Account ac=new Account();
Customer cust[]= new Customer[5];
for(int i=0;i<5;i++)
{
cust[i]=new Customer(ac);
}
for(int i=0;i<5;i++)
{
cust[i].start();
}
try
{
for(int i=0;i<5;i++)
{
cust[i].join();
}
}
catch(InterruptedException ie)
{
System.err.println(ie);
}
System.out.println("Total Balance:"+ac.getBalance());
}
}

OUTPUT

Current Balance:10
Current Balance:20
Current Balance:30
Current Balance:40
Current Balance:50
Total Balance:50

Note:

1) When we execute any synchronization based application (sync.java) on mono/single user OS then writing synchronized keyword is mandatory for obtaining a consistent result otherwise we get an inconsistent result because even though OS content synchronization concept it is not implemented in the mono operating system.

2) if we execute the above synchronization based application multithreaded operating system(Linux, Windows 7) then writing synchronized keyword is optional because this Operating system contains the implementation of synchronization. if we depend on an operating system based synchronization then we get inconsistent in order of update while execution but we get a final result is consistent. (Not Recommended).

3) Industry recommended, writing synchronized keyword irrespective of OS types, we are using at the same time of the running synchronized based application because java based synchronization is given consistently in order of operation and consistency in the final result as well.

Inter thread communication example


ITC concept in Java is one of the specialized forms of IPC(inter-process communication) of OS. In the Real world, ITC based applications are known as the fastest application. The consistent mechanism of exchanging the data between multiple threads is known as ITC.

The consistent mechanism of exchanging data between multiple threads is known as ITC. If the output of first aid is given as an input to the second thread, the output of the second thread is given as an input to the third thread etc then the consistent communication between the first second and third thread is known as ITC.

Real world implementation of ITC

1) development of Universal protocols
2) development of real-world server software

To develop the inter-thread communication application we use the methods which are presenting java.lang.Object and these methods are called ITC methods.

ITC methods in java.lang.Object

1) public final void wait(long)
2) public final void wait()
3) public final void notify()
4) public final void notifyAll()

“method 1” is used for making the current thread to wait in the form of time until CPU burst time of previous thread is completed. This method is not advisable to use practically because Java program cannot decide CPU burst time of previous thread to make the current thread to wait.

“method 2” is used for making the current thread to wait without time until previous thread completed its execution. This method is more advisable to use to make the current thread to wait because, with the programming technique, we cannot determine whether the previous thread is completed or not.

The above one and two methods throw a predefined exception called InterruptedException.

“method 3” is used for transferring one thread at a time from waiting for the state to the ready state.

“method 4” used for transferring all the Threads from waiting for the state to ready state.

The classical example of ITC(original from IPC)


1) producer-consumer problem
2) dining philosopher problem
3) readers-writers problem
4) burger shop problem

Implementation of producer-consumer problem


Producer: Producer is one of the thread which will always produce the values. At any point in time producer that will produce only one item.
Consumer: Consumer is one of the thread which will consume the items which are produced by producer thread. At any point of a time, consumer thread will consume only one value at a time.

The following diagram used implementation of producer consumer problem


producer consumer problem

Here consistent communication between producer and consumer thread is known as inter thread communication.

Write a java program which will implement producer consumer problem.


package com.ravi.java;
class Q
{
boolean valSet=false;
int n;
synchronized void put(int i)
{
try
{
if(valSet)
{
wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
n=i;
System.out.println("PUT:"+i);
valSet=true;
notify();
}//put()
synchronized int get()
{
try
{
if(!valSet)
{
wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("GOT:"+n);
valSet=false;
notify();
return(n);
}//get()
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
Thread pt=new Thread(this);
pt.start();
}
public void run()
{
int i=0;
while(true)
{
q.put(++i);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
Thread ct=new Thread(this);
ct.start();
}
public void run()
{
while(true)
{
int x=q.get();
}
}
}
public class Producer_Consumer
{
public static void main(String[] args)
{
Q q=new Q();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
}
}

OUTPUT

PUT:163494
GOT:163494
PUT:163495
GOT:163495
PUT:163496
GOT:163496
PUT:163497
GOT:163497
PUT:163498
GOT:163498
PUT:163499
GOT:163499

Press ctrl+c to terminate.

Kindy suggests if we missed something to mention in this, So we will improve this blog post as well.

Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *