Skip to main content

Multithreading

Multithreading in java is a process of executing multiple threads simultaneously. Usually used in games.

There are two ways of creating a Thread.

By extending Thread class

class MultiClass extends Thread {

public void run() {
System.out.println("thread method started…");
}

public static void main(String args[]) {
MultiClass t1=new MultiClass ();
t1.start();
}
}

By implementing Runnable interface

class MultiClass implements Runnable {

public void run() {
System.out.println("Thread is running...");
}

public static void main(String args[]) {
MultiClass mc1=new MultiClass ();
Thread t1 =new Thread(mc1);
t1.start();
}
}

Synchronization

In multi-threaded environment, if we need to make a resource available to one thread at a time, we use synchronization. The synchronization keyword in java creates a block of code called critical section (which can be used by only one thread at a time using lock).

Inter process communication

Two or more threads can interact with each other using three methods such as

  • wait() (Release the lock & make the thread suspended)
  • notify() (Release the lock & Resumes a thread which is suspended)
  • notifyAll() (Release the lock & Resumes all thread which are suspended)