DEV Community

Anupam Tarai
Anupam Tarai

Posted on • Updated on

Thread In Java

  • A thread is a small part of a process capable of execute independently.
  • Java supports multithreading, allowing a process to be divided into multiple threads. These threads can be scheduled by the CPU to execute in parallel, improving the performance of the application.

Creation of a Thread

  • We can create a thread by extending the 'Thread' class or implementing the 'Runnable' interface. Override the run method inside the thread.

CODE

class A extends Thread{ //A is a thread that extends "Thread" class
    public void run(){ //Override the run method
        for (int i=0; i<10; i++){
        System.out.println("AAAA");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class B implements Runnable{ //B is a thread that impliments "Runnable" interface
    public void run(){ //Override the run method
        for (int i=0; i<10; i++){
            System.out.println("BB");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class Server {
   public static void main(String[] args){
        A a = new A();
        B b = new B();
        Thread Tb = new Thread(b); // we need to pass that runnable into the costructor of thread class to create a thread
        a.start();
       try {
           Thread.sleep(10);
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       }
       Tb.start();

    }
}

Output:
AAAA
AAAA
BB
BB
AAAA
AAAA
BB
AAAA
BB
BB
AAAA
BB
AAAA
AAAA
BB
BB
AAAA
BB
AAAA
BB

Enter fullscreen mode Exit fullscreen mode

Here we have two classes, A and B, both representing threads. When we start the threads using the start method, both threads begin executing in parallel.

Methods in the Thread Class

  • start(): Starts the thread's execution; the JVM calls the thread's run method.
  • run(): Contains the code to be executed by the thread.
  • join(): Waits for the thread to die. If called on a thread, the calling thread will wait until the thread on which join was called finishes.
  • sleep(long millis): Causes the current thread to sleep for the specified number of milliseconds.
  • interrupt(): Interrupts the thread, causing it to stop its current task and handle the interruption (if it checks for interruptions).

CONCLUSION

Threads are helpful in large applications that require more time and resources to execute. By dividing such applications into multiple threads and executing them in parallel, the performance of the application can be significantly increased.

Please comment below if I have made any mistakes or if you know any additional concepts related to this topic.

Top comments (0)