Multithreading in Java

Multi-threading is a process in which two or more threads (a lightweight sub process) execute simultaneously. Each part of a program is called a thread.

  • Threads share the same address space
  • A Thread is lightweight
  • Cost of communication between the threads is low
  • At least one process is required for each thread

 

Firstly, a program comes in a new state, then it moves to a runnable state. If we give the “run” command on the runnable state, then it will move to a running state, at the running state, if we give the “yield” command, then the program returns to the runnable state. For blocking the thread from being in the runnable state, we can use suspend, sleep or wait. If we use the “stop” method at any state, then our program will move to the “dead” state.

Blocking a thread
  • Sleep - Sleep method blocks a thread for a specified time. Ex. Sleep (time in millisecond)
  • Suspend - It blocks the thread until the further order. The thread can be revived by the “resume” method
  • Wait - Wait blocks the thread until a certain condition occurs. The thread can be revived by using the “notify” method