Threads In Java.

 Thread In Java 🧡





Java Threads

Threads help a software to work more effectively by allowing it to do numerous tasks at once.


Threads allow complex activities to be completed in the background without interrupting the main programme.



Creating a Thread

A thread could be made in two ways.


  1. It's possible to create one by extending the Thread class and overriding the run() method.

  2. Another way to create a thread is to implement the Runnable interface.


Running Threads

  1. Extend Example : 

      public class Main extends Thread {
        public static void main(String[] args) {
          Main thread = new Main();
          thread.start();
          System.out.println("This code is outside of the thread");
        }
        public void run() {
          System.out.println("This code is running in a thread");
        }
      }
    
  2. Implement Example : 

    public class Main implements Runnable {
      public static void main(String[] args) {
        Main obj = new Main();
        Thread thread = new Thread(obj);
        thread.start();
        System.out.println("This code is outside of the thread");
      }
      public void run() {
        System.out.println("This code is running in a thread");
      }
    }

Threads: The Differences Between "Extending" and "Implementing"πŸ‘―

      The main difference is that a class that extends the Thread class cannot
extend any other class, whereas a class that implements the Runnable
interface can extend from any other class, such as: class MyClass extends
OtherClass implements Runnable.


π“Έπ“Έπ“ΈπŸ‘π“Έπ“Έπ“Έ

Popular Posts

Family Tree Project in Java

java:17: error: local variables referenced from a lambda expression must be final or effectively final count ++ ;

Creating basic tic tac toe android app using java