Threading In Java

What is Thread?

  1. Thread is light weight process (Mini Process).
  2. Thread is a part of a process and has its own call by stack memory.
  3. Thread can also use the share memory.
  4. Each java program executes by using thread, this thread created by JVM internally.
  5. The default thread which is created by JVM is known as main thread.
  6. Thread cannot be execute manually, it will automatically executes by JVM.
  7. You cannot completely predict the thread execution, and thread can be produce different out on different system.

Advantage of Thread

  1. Multithreaded applications provide faster performance.
  2. If any of the thread stop executing due to any reason then whole process will not terminate. And other thread from the process can still run.

What is Process?

  1. It is a heavy weigh application.
  2. Each process requires large memory and resources.
  3. Thread is part of this process.
  4. Multi-tasking means executing multiple process at a same time.
  5. Once process can have any number of threads.

 

How To Know Default Thread In Java

To know what is default thread in java we can use Thread.currentThread() Method.

Example :-

public class DefaultThread {

	public static void main(String[] args) {
		System.out.println(Thread.currentThread());

	}

}

 

How to create Thread in Java

  1. There are two ways to create a thread.
    1. Runnable Interface
    2. Thread class
  2. Thread class internally implements Runnable interface.

Thread By Runnable Interface Example :-

public class ThreadByRunnable {

	public static void main(String[] args) {
		Printer p = new Printer();
		Thread t = new Thread(p);
		t.start();
	}
}
class Printer implements Runnable {

	@Override
	public void run() {
		System.out.println("Created Thread by using runnable interface");
		System.out.println(Thread.currentThread());
	}
	
}

 

Thread By Thread Class Example :-

public class CustomThreadIntro {

	public static void main(String[] args) {
		System.out.println("====main thread statred====");
		Thread main =Thread.currentThread();
		main.setPriority(1);
		CustomThread custom = new CustomThread();
		custom.setPriority(10);
		custom.setName("New Thread");
		custom.start();
		System.out.println(Thread.currentThread());
		System.out.println("====main thread end====");
	}

}
class CustomThread extends Thread {
	public void run() {
		System.out.println("Custom thread started===========");
		//System.out.println(10/0);
		System.out.println("This is my first custom thread");
		System.out.println(Thread.currentThread());
		System.out.println("===========Custom thread ended");
	}
}

 

 

Thread class Methods

MethodsDescription
Thread.currentThread()This is a static method which return the object of currently executed thread, Object prints the details of current thread
Example: Thread[main,5,main]
1. Is name of thread
2. Thread priority
3. Thread group/ parent thread.
run()In side this method you can assign the task to a thread. This method has to override from Runnable or Thread class.
start()This method is use to make thread ready to run. This will not start the execution of the thread.
setName(String)
getName()
These methods are use to set and get the thread name.
setPriority(int)
getPriority()
These methods are use to set and get the priority of the thread. Priority Must be between 1 to 10, else it will throw an exception.
1 – MIN Priority
5 – MID/NORMAL Priority
10 – MAX Priority
join()

join(long)

join(long, int)

Join method will pause the execution of current thread either wait for the completing execution of anther thread or until given time expires. Join method is non static method. It throws an interruptedException checked exception. In case of Synchronization it will not releases the lock.
sleep(long)

sleep(long,int)

Sleep method will pause the execution of current thread for specific time.

Sleep method is a static method. It throws an interruptedException checked exception. In case of Synchronization it will not releases the lock.

wait()
wait(long)
wait(long,int)
It will pause the execution of current thread, and go into waiting stage, also it will release the lock. Wait method has to use in synchronized block or method. This method is available inside Object class and not in Thread class. It throws an interruptedException checked exception.
notify()It will give the notification for the any single thread which is waiting for object lock. This method is available inside Object class. method has to use in synchronized block or method.
notifyAll()It will give the notification for all threads which are waiting for object lock. This method is available inside Object class. method has to use in synchronized block or method.

 

Thread Life Cycle

  1. Thread life cycle will be manage by JVM
  2. There are 5 stages of thread life cycle
    1. New/Born Stage: whenever you create object of thread class of its sub-class
    2. Runnable stage: thread is ready to run.
    3. Running Stage: Thread will perform execution
    4. Dead/Terminate: after completing execution thread enters into this stage.
    5. Pause/Sleep/Wait: The execution of the thread will pause here and will not be picked by JVM for execution

 

Thread Life Cycle

Example :-

public class ThreadSleepJoin {

	public static void main(String[] args) {
		PrintPattern t2 = new PrintPattern();
		PrintTable t1 = new PrintTable(t2);
		t1.start();
		t2.start();
		try {
			t1.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("main thread end.........");
	}
}
class PrintTable extends Thread {
	PrintPattern p;
	public PrintTable(PrintPattern t2){
		this.p =t2;
	}
	public void run() {
		try {
			p.join(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for(int i = 1; i<=10; i++) {
			System.out.println("5 * "+i+" = "+(5*i));
		} 
	}
}
class PrintPattern extends Thread{
	public void run() {
		for(int i = 1;i<=5;i++) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			for(int j = 1;j<=i;j++) {
				System.out.print("* ");
			}
			System.out.println();
		}
	}
}

 

 

Synchronization

  1. It is use to lock and unlock the share resources.
  2. synchronized is a keyword, which can be use for a method or can create synchronized block.
  3. Synchronized cannot be use for a variable and class.
  4. When synchronized is used, then Object will gets lock and it will releases automatically once the execution is done.
  5. Synchronized Block Syntax:

synchronized(object-to-be-lock) {

//statement(s)

}

Example :-

public class SynchronizationDemo {
	public static void main(String[] args) {
		ZeroxMech zerox = new ZeroxMech();
		Customer1 c1 = new Customer1(zerox);
		c1.setName("Customer1");
		Customer2 c2 = new Customer2(zerox);
		c2.setName("Customer2");
		
		c1.start();
		c2.start();
		
	}
}
class Customer1 extends Thread {
	private ZeroxMech zerox;
	public Customer1(ZeroxMech zerox) {
		this.zerox = zerox;
	}
	public void run() {
		synchronized (zerox) {
			for(int i =1; i<=10 ; i++) {
				zerox.print(getName() + " : " + i);
				try {
					
					if(i==5) {
						zerox.wait(1000);
					}
					
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

class Customer2 extends Thread {
	private ZeroxMech zerox;
	public Customer2(ZeroxMech zerox) {
		this.zerox = zerox;
	}
	public void run() {
		synchronized (zerox) {
			for(int i =1; i<=10 ; i++) {
				String val = "5 * "+ i + " = "+ (5*i);
				zerox.print(getName() + " : " + val);	
			}
			//zerox.notify(); //to notify single thread
			//zerox.notifyAll(); //to notify multiple thread
		}
	}
}

class ZeroxMech {
	//public synchronized void print(String val) { //syntax for synchronized method
	public void print(String val) {
		System.out.println(val);
	}
}

 

Thread FAQ
  1. What is thread? How to create thread?
  2. What is the difference between multi threading and multi tasking.
  3. Advantage of using Thread in application.
  4. Life cycle of thread.
  5. Different methods for thread class.
  6. Difference between Sleep, Join, Wait methods
  7. Difference between Notify, NotifyAll methods
  8. What is synchronization? How to use synchronization.
  9. Advantages and Disadvantage of Synchronization.

 

Join Telegram : Click Here

 

All Full Stack Java Study Material

 

Java the programing language

 

Job’s For Fresher

 

Share This Information To Your Friends and Your College Group’s, To Help Them !

India Flag Just Update New Vacancy