Thread:

  • Directly represents a thread.
  • Encapsulates both the thread’s creation and execution.
  • Less flexible due to the single inheritance constraint.

Creating a Thread by Extending the Thread Class:

class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}

public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Creating an instance of MyThread
t1.start(); // Starting the thread
}
}

Runnable:

  • Represents a task to be executed by a thread.
  • More flexible, allowing the class to inherit from other classes.
  • Encouraged for scenarios where you need to separate task definition from thread management.

Creating a Thread by Implementing the Runnable Interface:

class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running.");
}
}

public class RunnableExample {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable(); // Creating an instance of MyRunnable
Thread t1 = new Thread(runnable); // Creating a Thread instance and passing the Runnable object
t1.start(); // Starting the thread
}
}

Hinterlasse einen Kommentar

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect