- Creating and Running a Thread using Runnable Interface
- How life cycle of a thread in works in Java ?.
- How to put a thread to sleep in Java ?.
- How to set a thread's priority in Java ?.
- How to interrupt a thread in Java ?
- How to create synchronized threads in Java ?.
- How to get name of current executed method and list of methods executing on the stack of main Thread in Java?
- How to create a thread by extending the Thread class ?.
Free Data Structures and Algorithms Course
Showing posts with label Multithreading in Java. Show all posts
Showing posts with label Multithreading in Java. Show all posts
Multithreading in Java
How to create a thread by extending the Thread class ?.
Program to demonstrate creation of a thread by extending the Thread class in Java
package com.hubberspot.multithreading;
public class ProducerConsumerTest {
public static void main(String[] args) {
// 3. Create a thread by instantiating
// an object from the class
Thread producer = new Producer();
Thread consumer = new Consumer();
// 4. Call the start() method of the
// thread object
producer.start();
consumer.start();
// Overall three threads are created
// 1. for main method , 2. for the Producer class
// 3. for the Consumer class
}
}
// 1. Create a class that extends Thread
class Producer extends Thread {
// 2. Overload the run method to perform
// the desired task
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("I am Producer : Produced Apple " + i);
// static method that pause current thread so that other thread
// gets the time to execute
Thread.yield();
}
}
}
class Consumer extends Thread {
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("I am Consumer : Consumed Apple " + i);
Thread.yield();
}
}
}
Output of the program : How to get name of current executed method and list of methods executing on the stack of main Thread in Java?
ADHREQQGA7TT
Program to demonstrate how to get name of current executed method and list of methods executing on the stack of main Thread in Java.
ADHREQQGA7TT
Program to demonstrate how to get name of current executed method and list of methods executing on the stack of main Thread in Java.
package com.hubberspot.example;
public class CurrentExecutedMethodName {
public static void main(String[] args) {
System.out.println("In method : main()");
// Getting the Current Thread executing main method
Thread thread = Thread.currentThread();
// Getting an array of elements on stack trace of thread
StackTraceElement[] stackTraceElements = thread.getStackTrace();
// Using the getMethodName() of StackTraceElement
// We obtain the executing method on the stack
System.out.println("Method name is : "+
stackTraceElements[1].getMethodName());
// Adding yet another method on the stack
methodA();
}
private static void methodA() {
System.out.println("In method : methodA()");
Thread thread = Thread.currentThread();
StackTraceElement[] stackTraceElements = thread.getStackTrace();
System.out.println("Method name is : "+
stackTraceElements[1].getMethodName());
// Adding yet another method on the stack
methodB();
}
private static void methodB() {
System.out.println("In method : methodB()");
Thread thread = Thread.currentThread();
StackTraceElement[] stackTraceElements = thread.getStackTrace();
System.out.println("Method name is : "+
stackTraceElements[1].getMethodName());
// Adding yet another method on the stack
methodC();
}
private static void methodC() {
System.out.println("In method : methodC()");
Thread thread = Thread.currentThread();
StackTraceElement[] stackTraceElements = thread.getStackTrace();
System.out.println("Method name is : "+
stackTraceElements[1].getMethodName());
// Adding yet another method on the stack
// This method will print list of all methods
// on the stack trace waiting for the execution
completeStackTrace();
}
private static void completeStackTrace() {
System.out.println("In method : completeStackTrace()");
Thread thread = Thread.currentThread();
StackTraceElement[] stackTraceElements = thread.getStackTrace();
System.out.println();
System.out.println("Printing Complete Stack Trace ... \n");
// Looping the StackTraceElements and printing
// the methods of it
for(int i = 0; i< stackTraceElements.length; i++) {
System.out.println("Method at "+ i +" : "+
stackTraceElements[i].getMethodName());
}
}
}
Output of the program : ADHREQQGA7TT
How to create synchronized threads in Java ?.
Whenever there is an application or program which tends to deal with two or more threads, has to deal with concurrency issues as well.
Concurrency issues are due to conflicts between two or more threads attempting to change state of same object. This might result into inaccurate results for other threads.
So to overcome this problem we use synchronize keyword before a block of code or method declaration.
After placing synchronized keyword as shown below , the JVM guarantees/ensures that if any thread is accessing synchronized block of code, no other thread will able to access the block of code till the first one is done with its modifications.
package com.hubberspot.multithreading;
public class SynchronizedThreads{
private String name;
// Using synchronized keyword over a method or
// block of code makes it locked for thread
public synchronized String getName() {
return this.name;
}
public synchronized void setName(String name) {
this.name= name;
}
public void displayName(){
System.out.println("The name is : " + name);
}
}
How to interrupt a thread in Java ?
Program to demonstrate how to interrupt a thread in Java
package com.hubberspot.multithreading;
public class InterruptedThread {
public static void main(String[] args) {
// 3. Create a thread by instantiating
// an object from the class
Thread count = new Counter();
// 4. Call the start() method of the
// thread object
count.start();
for(int i = 0; i < 100; i++) {
// loops through till i == 5
// interrupts the Counter class thread at
// i==5
if(i == 5){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(i == 5){
// Calling interrupt method on
// count object
count.interrupt();
}
}
}
}
class Counter extends Thread {
public void run(){
int i = 0;
// Till the thread is not interrupted
// it loops and prints count
while(!isInterrupted()){
System.out.println("Count is " + i++);
try {
// Have a pause so that
// as soon as interruption occur
// it throws InterruptedException and
// thread of Counter class gets interrupted
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
System.out.println("Thread Interrupted");
}
}
Output of the program :
How to set a thread's priority in Java ?.
Program to demonstrate how to set a thread's priority in Java
package com.hubberspot.multithreading;
public class ProducerConsumerTest {
public static void main(String[] args) {
// 3. Create a thread by instantiating
// an object from the class
Thread producer = new Producer();
Thread consumer = new Consumer();
// 4.(i) Give Producer class thread a priority of 1
// i.e. it has minimum priority
producer.setPriority(Thread.MIN_PRIORITY);
// 4.(ii) Give Consumer class thread a priority of 10
// i.e. it has maximum priority
consumer.setPriority(Thread.MAX_PRIORITY);
// 5. Call the start() method of the
// thread object
producer.start();
consumer.start();
// Overall three threads are created
// 1. for main method , 2. for the Producer class
// 3. for the Consumer class
}
}
// 1. Create a class that extends Thread
class Producer extends Thread {
// 2. Overload the run method to perform
// the desired task
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("I am Producer : Produced Apple " + i);
// 1. one way to put thread to sleep
// static method that pause current thread so that other thread
// gets the time to execute
//Thread.yield();
}
}
}
class Consumer extends Thread {
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("I am Consumer : Consumed Apple " + i);
//Thread.yield();
}
}
}
Output of the program : How to put a thread to sleep in Java ?.
Program to demonstrate how to put a thread to sleep in Java using yield and sleep method
package com.hubberspot.multithreading;
public class ProducerConsumerTest {
public static void main(String[] args) {
// 3. Create a thread by instantiating
// an object from the class
Thread producer = new Producer();
Thread consumer = new Consumer();
// 4. Call the start() method of the
// thread object
producer.start();
consumer.start();
// Overall three threads are created
// 1. for main method , 2. for the Producer class
// 3. for the Consumer class
}
}
// 1. Create a class that extends Thread
class Producer extends Thread {
// 2. Overload the run method to perform
// the desired task
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("I am Producer : Produced Apple " + i);
// 1. one way to put thread to sleep
// static method that pause current thread so that other thread
// gets the time to execute
Thread.yield();
try {
// 2. another way to thread to sleep
// It takes an argument of int which
// specifies time in milliseconds for
// pausing or making a thread sleep.
// Generally, thread goes to blocked state
// for the time specified... here its 1 second
Thread.sleep(1000);
// Thread.sleep() method throws Interrupted Exception
// if something interrupts the thread on sleeping
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread {
public void run(){
for (int i = 0; i < 10; i++){
System.out.println("I am Consumer : Consumed Apple " + i);
Thread.yield();
try {
// 2. another way to thread to sleep
// It takes an argument of int which
// specifies time in milliseconds for
// pausing or making a thread sleep.
// Generally, thread goes to blocked state
// for the time specified... here its 2 seconds
Thread.sleep(2000);
// Thread.sleep() method throws Interrupted Exception
// if something interrupts the thread on sleeping
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Output of the program : How life cycle of a thread in works in Java ?.
Introduction to life cycle of a simple thread in Java :-
Life cycle of a thread in Java has many important states. These states defines the functionality and working of Java threads. There are normally five states through which a thread can go from birth to death. The states are as follows :-
Life cycle diagram of a thread in Java :-
Life cycle of a thread in Java has many important states. These states defines the functionality and working of Java threads. There are normally five states through which a thread can go from birth to death. The states are as follows :-
- New :- Whenever we instantiate an object of class Thread, we create a new thread which goes to new state. It is the state which signifies that a new thread is created but its not ready to run.
- Runnable :- After creation of thread when we call Thread's start method, it changes state of a thread from new to runnable. This transition does not make thread to run but it makes a thread eligible to run. After reaching this state thread gets a call from Java Thread Scheduler to run. Thread Scheduler selects one of the runnable thread after processor becomes available to it.
- Blocked :- Generally , threads can move to blocked state due to various reasons, some of the reasons are waiting for I/O operation , waiting for any network connections etc. Usually a thread gets back to its runnable state when it finishes its operation which has blocked it. A blocked thread can't be run by thread scheduler , it has to get back to runnable state to run.
- Waiting :- A thread can enter to a waiting state by calling wait method over it. It can go to runnable state whenever another thread calls notify or notifyAll method to send notification to it for getting back to runnable state.
- Terminate :- A thread terminates when run method completely executes itself. Once a thread terminates it never gets back to its runnable state.
Life cycle diagram of a thread in Java :-
Creating and Running a Thread using Runnable Interface
In order to create , execute and run a simple Thread in Java , we need to perform few operations . We can create a thread by two ways :
1 . First way is to create a thread by implementing Runnable Interface . Generally , Runnable Interface has one method called as run . This run method performs the logic for our thread . We have to provide implementation to this method from the Runnable Interface and execute it when we want to execute code in threads.
2 . Second way is to extend Thread class in Java and override run method .
Program to demonstrate creation and running of a Thread by implementing Runnable Interface
package com.hubberspot.multithreading.example ;
// Implementing Runnable Interface
class MyRunnable implements Runnable
{
// Implementing run method of Runnable
public void run( )
{
for( int i = 1 ; I < = 5 ; i++ )
System.out.println( " Message " + i ) ;
}
}
public class RunnableTest
{
public static void main( String[ ] args )
{
MyRunnable r = new MyRunnable( ) ;
Thread t = new Thread( r ) ;
System.out.println( t ) ;
// starting the thread by start method which will
// call run method internally
t.start( ) ;
}
}
Output of the program :
Subscribe to:
Posts (Atom)






