To make a thread begin its execution, call the start()
method on a Thread
or Runnable
instance. Then the Java Virtual Machine will calls the run method of this thread.
The snippet below is showing how to create a thread by implementing the Runnable
interface.
package org.kodejava.lang;
public class ThreadRun implements Runnable {
public static void main(String[] args) {
// Instantiate ThreadRun
ThreadRun runner = new ThreadRun();
// Create instance of Thread and passing ThreadRun object
// as argument.
Thread thread = new Thread(runner);
// By passing Runnable object, it tells the
// thread to use run() of Runnable object.
thread.start();
}
public void run() {
System.out.println("Running..");
}
}
The snippet below is showing how to create a thread by extending the Thread
class.
package org.kodejava.lang;
public class ThreadStart extends Thread {
public static void main(String[] args) {
ThreadStart thread = new ThreadStart();
// Start this thread
thread.start();
}
/**
* The run() method will be invoked when the thread is started.
*/
@Override
public void run() {
System.out.println("Running..");
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024