Multi-Threading

Thread:
  • It is a lightweight subprocess
  • It is smallest unit
  • It execute separately
  • All threads shares same memory
  • communication between threads is easy
Multithreading:
It process of running multiple threads at the same time.

States of Thread:


New:
It is first state of Thread where Object of Thread class is created

Runnable:
It is the state after start() method called  and thread is waiting for thread scheduler to assign resources

Running:
It is the state where code inside run method is currently executing

Blocked, Waiting and Timed_Waiting:
It is the state where a Thread is blocked, waiting and waiting for specified amount of time respectively

Terminated:
It is the last state where execution of all the code is completed inside run() method

Thread can mainly be created using two ways in Java
  1. Create a class that extends Thread class 
  2. Create a class that implements Runnable interface
Constructor of Thread class:
  1. Thread()
    Allocates a new Thread object.
  2. Thread(Runnable target)
    Allocates a new Thread object.
  3. Thread(Runnable target, String name)
    Allocates a new Thread object.
  4. Thread(String name)
    Allocates a new Thread object.
  5. Thread(ThreadGroup group, Runnable target)
    Allocates a new Thread object.
  6. Thread(ThreadGroup group, Runnable target, String name)
    Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
  7. Thread(ThreadGroup group, Runnable target, String name, long stackSize)
    Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
  8. Thread(ThreadGroup group, String name)
    Allocates a new Thread object.

Methods of Thread class:
  1. static int activeCount(): Returns an estimate of the number of active threads in the current thread's thread group and its subgroups.
  2. void checkAccess(): Determines if the currently running thread has permission to modify this thread.
  3. protected Object clone(): Throws CloneNotSupportedException as a Thread can not be meaningfully cloned.
  4. static Thread currentThread(): Returns a reference to the currently executing thread object.
  5. static void dumpStack(): Prints a stack trace of the current thread to the standard error stream.
  6. long getId(): Returns the identifier of this Thread.
  7. String getName(): Returns this thread's name.
  8. int getPriority(): Returns this thread's priority.
  9. StackTraceElement[] getStackTrace(): Returns an array of stack trace elements representing the stack dump of this thread.
  10. Thread.State getState(): Returns the state of this thread.
  11. ThreadGroup getThreadGroup(): Returns the thread group to which this thread belongs.
  12. static boolean holdsLock(Object obj): Returns true if and only if the current thread holds the monitor lock on the specified object.
  13. void interrupt(): Interrupts this thread.
  14. static boolean interrupted(): Tests whether the current thread has been interrupted.
  15. boolean isAlive(): Tests if this thread is alive.
  16. boolean isDaemon(): Tests if this thread is a daemon thread.
  17. boolean isInterrupted(): Tests whether this thread has been interrupted.
  18. void join(): Waits for this thread to die.
  19. void join(long millis): Waits at most millis milliseconds for this thread to die.
  20. void join(long millis, int nanos): Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
  21. void run(): If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
  22. void setDaemon(boolean on): Marks this thread as either a daemon thread or a user thread.
  23. void setName(String name): Changes the name of this thread to be equal to the argument name.
  24. void setPriority(int newPriority): Changes the priority of this thread.
  25. static void sleep(long millis): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
  26. static void sleep(long millis, int nanos): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.
  27. void start(): Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
  28. String toString(): Returns a string representation of this thread, including the thread's name, priority, and thread group.
  29. static void yield(): A hint to the scheduler that the current thread is willing to yield its current use of a processor.

Runnable:
  • It is an interface that has only one abstract method
  • public abstract void run()

Example 1:
package com.java.thread;

public class ThreadState extends Thread {
    public ThreadState(String name) {
        super(name);
    }
    public void run() {
        Thread t = Thread.currentThread();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(t + " has $" + t.getState() + "$ State");
    }
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new ThreadState("Thread 1");
        Thread thread2 = new ThreadState("Thread 2");
        Thread ct = Thread.currentThread();
        System.out.println(thread1 + " has \"" + thread1.getState() + "\" State" );
        System.out.println(thread2 + " has \"" + thread2.getState() + "\" State");
        System.out.println(ct + " has \"" + ct.getState() + "\" State");

        thread1.start();
        thread2.start();
        
        Thread.sleep(1000);
        
        System.out.println(thread1 + " has '" + thread1.getState() + "' State" );
        System.out.println(thread2 + " has '" + thread2.getState() + "' State");
        
        Thread.sleep(2000);
        System.out.println(thread1 + " has *" + thread1.getState() + "* State" );
        System.out.println(thread2 + " has *" + thread2.getState() + "* State");
        System.out.println(ct + " has *" + ct.getState() + "* State");
    }
}

Output:
Thread[Thread 1,5,main] has "NEW" State
Thread[Thread 2,5,main] has "NEW" State
Thread[main,5,main] has "RUNNABLE" State
Thread[Thread 1,5,main] has 'TIMED_WAITING' State
Thread[Thread 2,5,main] has 'TIMED_WAITING' State
Thread[Thread 1,5,main] has $RUNNABLE$ State
Thread[Thread 2,5,main] has $RUNNABLE$ State
Thread[Thread 1,5,] has *TERMINATED* State
Thread[Thread 2,5,] has *TERMINATED* State
Thread[main,5,main] has *RUNNABLE* State

Example 1:
ThreadPrime.java
package com.java.thread;

public class ThreadPrime implements Runnable {
    int num;
    
    public ThreadPrime(int num) {
        this.num = num;
    }
    
    public void run() {
        System.out.println("Prime numbers are : ");
        for (int i = 2; i <= num; i++) {
            if(isPrime(i)){
                System.out.println(i + " is Prime number");
            }
        }
    }
    
    public boolean isPrime(int n) {
        boolean flag = true;
        for (int i = 2; i <= n/2; i++) {
            if(n % i == 0){
                flag = false;
                break;
            }
        }
        if(flag) {
            return true;
        } else {
            return false;
        }
    }
}

ThreadPalindrome.java
package com.java.thread;

public class ThreadPalindrome extends Thread {
    int x;
    
    public ThreadPalindrome(int x) {
        this.x = x;
    }
    
    public void run() {
        for (int i = 1; i <= x; i++) {
            if(isPalindrome(i)){
                System.out.println(i + " is Palindrome");
            }    
        }
    }
    
    public boolean isPalindrome(int num) { 
        int temp = num, reverse = 0, remainder; 
        while(temp != 0) { 
            remainder = temp % 10; 
            reverse = reverse * 10 + remainder; 
            temp = temp / 10; 
        } 
        if(reverse == num) { 
            return true
        } 
        return false
    }
}

ThreadTest.java
package com.java.thread;

public class ThreadTest {
    public static void main(String[] args) {
        ThreadPalindrome palindrome = new ThreadPalindrome(100);
        ThreadPrime prime = new ThreadPrime(100);

        Thread t1 = new Thread(prime);
        Thread t2 = new Thread(palindrome);
        
        t1.start();
        
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t2.start();
        System.out.println("Main Thread");
    }
}

Output:
Prime numbers are :
2 is Prime number
3 is Prime number
5 is Prime number
7 is Prime number
11 is Prime number
13 is Prime number
17 is Prime number
19 is Prime number
23 is Prime number
29 is Prime number
31 is Prime number
37 is Prime number
41 is Prime number
43 is Prime number
47 is Prime number
53 is Prime number
59 is Prime number
61 is Prime number
67 is Prime number
71 is Prime number
73 is Prime number
79 is Prime number
83 is Prime number
89 is Prime number
97 is Prime number
Main Thread
1 is Palindrome
2 is Palindrome
3 is Palindrome
4 is Palindrome
5 is Palindrome
6 is Palindrome
7 is Palindrome
8 is Palindrome
9 is Palindrome
11 is Palindrome
22 is Palindrome
33 is Palindrome
44 is Palindrome
55 is Palindrome
66 is Palindrome
77 is Palindrome
88 is Palindrome
99 is Palindrome

No comments:

Post a Comment