Home > Java > javaTutorial > How to create thread using anonymous class in Java?

How to create thread using anonymous class in Java?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-08-26 22:37:06
forward
1181 people have browsed it

How to create thread using anonymous class in Java?

Threading is a function that can be executed simultaneously with other parts of the program. All Java programs have at least one thread, called the main thread, which is run by the Java Virtual Machine (JVM) when the program starts and when the main() method is executed. Created and called together with the main thread.

In Java, we can create threads by Extending threads Classor implement Runnable interface through . We can also create threads using anonymousclasswithout extending Thread classin the following program.

Example

public class AnonymousThreadTest {
   public static void main(String[] args) {
      new Thread() {
         public void run() {
            for (int i=1; i <= 5; i++) {
               System.out.println("run() method: " + i);
            }
         }
      }.start();
      for (int j=1; j <= 5; j++) {
         System.out.println("main() method: " + j);
      }
   }
}
Copy after login

Output

main() method: 1
run() method: 1
main() method: 2
run() method: 2
main() method: 3
run() method: 3
main() method: 4
run() method: 4
main() method: 5
run() method: 5
Copy after login

The above is the detailed content of How to create thread using anonymous class in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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