Sunday, June 22, 2014

Multithreading

Java multithreading | java thread | multithreading in java | java thread example

Threads: -“A thread is defined as the path of execution of a program.” Or we can say that threads is a light weighted process which runs concurrently with other threads. All threads of program defines a separate path of execution.
A process that is made of one thread is known as single threaded process. A process that creates two or more threads is called multithreaded process. Each thread in a multithreaded program runs at the same time and has a different execution path.

Multithreading: - Multithreading is a process of executing multiple thread simultaneously. Multithreading is used to achieve Multitasking.

Multitasking: - Multitasking is the ability to execute more than one task at the same time. Multitasking can be divided into following two categories:
  • Process based Multitasking (Multiprocessing)
  • Thread based Multitasking (Multithreading)
Process based multitasking is the feature of Java which enable to switch from one program to another so quickly that it appears as if the programs are executing at the same time. In Process based multitasking each process have its own address space in memory.
In Thread based multitasking threads share the same address space.

Advantages of Multithreading: -

  • Improved Performance
  • Minimized system resource usage
  • Simultaneous access to multiple applications
  • Program structure simplification

Disadvantages of Multithreading: -

  • Deadlock condition: - when two threads wait for each other to complete their operations before performing their individual action. As a result the two threads become locked.
  • Race condition: -when two or more threads simultaneously access the same variable, and at least one thread tries to write a value in this variable.
  • Lock starvation: - when the execution of a threads is postponed because of its low priority.

Example of Multithreading in JAVA: -

There are two ways to create a thread: -
  • By extending Thread class
  • By implementing Runnable interface
Here we implement the Thread example by using Runnable interface.


Notice how the order changes randomly in the output screen.

No comments:

Post a Comment