MultiThreading in Java

How to create thread

There are two ways to create a thread:

  • By extending Thread class
  • By implementing Runnable interface.
Threads implementation in java

Threads implementation in java

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

By extending Thread class

public class Main {

public static void main(String[] args)  {

Hello h = new Hello();

World w = new World();

h.start();

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

w.start();

}

}

class Hello extends Thread{

public void run()

{

for (int i = 1; i < 10; i++) {

System.out.println("Hello");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class World extends Thread{

public void run()

{

for (int i = 1; i < 10; i++) {

System.out.println("World");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

 

By implementing Runnable interface.

public class RunnableDemo {

public static void main(String[] args) throws InterruptedException {

Hello1 h = new Hello1();

World1 w = new World1();

Thread t1 = new Thread(h);

Thread t2 = new Thread(w);

t1.start();

t2.start();

System.out.println(t1.isAlive());

t1.join();

t2.join();

System.out.println("Completed");

System.out.println(t1.isAlive());

}

}

class Hello1 implements Runnable{

public void run()

{

for (int i = 1; i < 10; i++) {

System.out.println("Hello");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class World1 implements Runnable{

public void run()

{

for (int i = 1; i < 10; i++) {

System.out.println("World");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

 

Creating Thread with Block

public class ThreadBlock {

public static void main(String[] args) throws InterruptedException {

Thread t1 = new Thread(new Runnable() {

@Override

public void run() {

for(int i=0; i<50;i++)

{

System.out.println("Hello");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

});

Thread t2 = new Thread(new Runnable() {

@Override

public void run() {

for(int i=0; i<50;i++)

{

System.out.println("World");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

});

t1.start();

//Thread.sleep(200);

t2.start();

}

}

 

Synchronized Demo

Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to remember for Synchronized block

Synchronized block is used to lock an object for any shared resource.

Scope of synchronized block is smaller than the method.

public class SyncDemo {

public static void main(String[] args) throws InterruptedException {

WishtoSomeone ws = new WishtoSomeone();

MyThread t1=new MyThread(ws,"Abdul");

t1.start();

MyThread t2=new MyThread(ws,"Raju");

t2.start();

}

}

class WishtoSomeone{

public synchronized void wish(String name) {

for (int i = 0; i < 10; i++) {

System.out.print("Hello :");

try {

Thread.sleep(200);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(name);

}

}

}

class MyThread extends Thread{

WishtoSomeone ws;

String name;

public MyThread(WishtoSomeone ws,String name) {

this.ws=ws;

this.name=name;

}

public void run() {

ws.wish(name);

}

}

 

present in Object Class

  • Wait
  • Notify
  • NotifyAll
Waiting Thread in Java

Waiting Thread in Java

Reason why these method not available in Thread class

Our custom creation object example customer or student inside it wait and notify method are not available so it is there in object.

Postman story

Here t1 after calling wait method t1 goes to waiting state

T2 will do some process on the object and once finish it will give notification means it will called notify method so that t1 will process on the same project.

Thread States

Thread state in java

Thread state in java

If we called wait and notify method in non synchronized method then we get Exception illegalmonitorstateexception

public class WaitNotifyExample {

public static void main(String[] args) throws InterruptedException {

ThreadA t1 = new ThreadA();

t1.start();

//t1.join();

synchronized(t1)

{

//Main thread calling wait

t1.wait();

//Now Maint thread went into wait state

System.out.println(t1.total);

}

}

}




class ThreadA extends Thread{

int total=0;

public synchronized void run() {

synchronized(this)

{

for (int i = 0; i <1000; i++)

{

total=total+1;

}

//Thread A calling Notify method

//By calling notify method main thread get into running state

this.notify();

}




}

}

 

Note : Here we can call join method to get the same result but Recommended is wait method

Why because

for (int i = 0; i <1000; i++)

{

total=total+1;

}

//Thread A calling Notify method

//By calling notify method main thread get into running state

this.notify();

//After for loop 10000 lines are there

// then main thread wait until all lines execution finish

 

Notify All

Bus Example story narration

Deadlock

If two thread are waiting for each other that is known as deadlock

1st thread is waiting for second thread activity and 2nd thread is waiting for first thread activity both are waiting is know as deadlock.

Synchronized keyword is the only reason for deadlock hence need to take special care before using synchronized keyword.