Wednesday, 17 June 2015

Difference between Thread and Process in Java

In concurrent programming, there are two basic units of execution -

  • processes
  • thread
It is very important to know the difference between these two.

A process, in a way, is an executing instance of an application. Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. As example, running a Java IDE to write a Java program and visiting a web site at the same time.

A thread exists within a process and it is a path of execution within a process. This means that a single program can perform two or more tasks simultaneously. As example a word processor that is printing a document using a background thread and formatting text at the same time using another thread.

Process Vs Thread in Java

Let's see the differences between the thread and process in Java to have a clear idea what exactly is thread and what is process in Java.

  1. A process has a self-contained execution environment, Threads exist within a process - every process has at least one.
  2. Process are heavyweight tasks whereas threads are referred as lightweight processes as creating a new thread requires fewer resources than creating a new process.
  3. Each Process has its own separate address spaces, threads with in the same process share the process' resources, including memory and open files. This means that it's very easy to share data among threads, but it's also easy for the threads to bump on each other, which can lead to unpredictable scenarios like deadlock and race condition in multi-threading.
  4. Inter process communication is expensive whereas inter thread communication is inexpensive and in Java can be achieved easily using wait and notify.
  5. Context switching from one process to another is expensive; context switching between threads is generally less expensive than in processes.
  6. Threads are easier to create than processes as separate address space is not required for a thread.

That's all for this topic Difference between thread and process in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Can we start the same thread twice in Java
  2. Creating thread in Java
  3. Thread states in Java multithreading
  4. What if run() method called directly instead of start() method
  5. Synchronization in Java multithreading
  6. Java Multi-threading interview questions

You may also like -

1 comment:

  1. Short and crisp, best post! I like it that it is not prolonged just for the sake of having more words in the post! Keep writing like this.

    ReplyDelete