Runnable or Thread
Java multithreading
Thread is a block of code which can be execute concurrently with other threads in the JVM. To implement Java thread is just to specify what code a thread should run.
extends Thread class
create a subclass of Thread and override the run() method:
public class MyThread extends Thread {
public void run(){
System.out.println("MyThread running");
}
}
public class Teisei {
public static void main(String args[]){
Thread thread = new MyThread();
thread.start();
}
}
you can also create an anonymous subclass of Thread like this:
Thread thread = new Thread(){
public void run(){
System.out.println("Thread Running");
}
}
thread.start();
implement interface java.lang.Runnable
public class MyRunnable implements Runnable {
public void run(){
System.out.println("MyRunnable running");
}
}
To have the run() method executed by a thread, pass an instance of MyRunnable to a Thread in its constructor.
Thread thread = new Thread(new MyRunnable());
thread.start();
You can also create an anonymous implementation of Runnable, like this:
Runnable myRunnable = new Runnable(){
public void run(){
System.out.println("Runnable running");
}
}
Thread thread = new Thread(myRunnable);
thread.start();
Subclass or Runnable?
The most common difference is
- extend Thread class, you can’t extend any other class which you required.
- implement Runnable interface, you can save a space for your class to extend any other class in future or now.
The significant difference is
public class Teisei {
public static void main(String args[]){
System.out.println("Hello world! This is Teisei's blog");
}
}
If you like this post or if you use one of the Open Source projects I maintain, say hello by email. There is also my Amazon Wish List. Thank you ♥
Comments