Home > Java > javaTutorial > body text

How to create a thread in Java without implementing Runnable interface?

PHPz
Release: 2023-09-12 10:29:06
forward
1166 people have browsed it

How to create a thread in Java without implementing Runnable interface?

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

Example

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);
      }
   }
}
Copy after login

Output

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template