Threads can be called lightweight processes. Java supports multithreading, so it allows our application to perform two or more tasks simultaneously. All Java programs have at least one thread, called the main thread, which is created by the Java Virtual Machine (JVM) when the program starts. () The method is called in the main thread. There are two ways to create a thread in Java, one is extend the Thread class, and the other isimplement the Runnable interface.
We can also create a program in the following withoutimplementationRunnableinterface
public class CreateThreadWithoutImplementRunnable { <strong>//</strong> without implements Runnable public static void main(String[] args) { new Thread(new Runnable() { public void run() { for (int i=0; i <= 5; i++) { System.out.println("run() method of Runnable interface: "+ i); } } }).start(); for (int j=0; j <= 5; j++) { System.out.println("main() method: "+ j); } } }
main() method: 0 run() method of Runnable interface: 0 main() method: 1 run() method of Runnable interface: 1 main() method: 2 run() method of Runnable interface: 2 main() method: 3 run() method of Runnable interface: 3 main() method: 4 run() method of Runnable interface: 4 main() method: 5 run() method of Runnable interface: 5
The above is the detailed content of How to create a thread in Java without implementing Runnable interface?. For more information, please follow other related articles on the PHP Chinese website!