1. Introduction
In this quick article, You'll learn how to create a thread without extending the Thread class and implementing the Runnable interface.
2. Create Thread Without Extending Thread Class - Anonymous Thread
package com.javaprogramto.threads; public class AnonymousThreadExample { public static void main(String[] args) { new Thread() { public void run() { for (int i = 0; i <= 10; i++) { System.out.println( "Executing " + i + " thread name - " + Thread.currentThread().getName()); } } }.start(); for (int i = 0; i <= 10; i++) { System.out.println( "Executing " + i + " thread name - " + Thread.currentThread().getName()); } } }
Output:
Executing 0 thread name - mainExecuting 0 thread name - Thread-0Executing 1 thread name - mainExecuting 1 thread name - Thread-0Executing 2 thread name - mainExecuting 2 thread name - Thread-0Executing 3 thread name - mainExecuting 3 thread name - Thread-0Executing 4 thread name - mainExecuting 4 thread name - Thread-0Executing 5 thread name - mainExecuting 5 thread name - Thread-0Executing 6 thread name - mainExecuting 6 thread name - Thread-0Executing 7 thread name - mainExecuting 7 thread name - Thread-0Executing 8 thread name - mainExecuting 8 thread name - Thread-0Executing 9 thread name - mainExecuting 9 thread name - Thread-0Executing 10 thread name - mainExecuting 10 thread name - Thread-0
3. Create Thread Without Implementing Runnable Interface - Anonymous Runnable
package com.javaprogramto.threads;public class AnonymousRunnableExample {public static void main(String[] args) {new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i <= 10; i++) {System.out.println("Executing " + i + " thread name - " + Thread.currentThread().getName());}}}).start();for (int i = 0; i <= 10; i++) {System.out.println("Executing " + i + " thread name - " + Thread.currentThread().getName());}}}
Output:
Executing 0 thread name - Thread-0Executing 0 thread name - mainExecuting 1 thread name - Thread-0Executing 1 thread name - mainExecuting 2 thread name - Thread-0Executing 2 thread name - mainExecuting 3 thread name - Thread-0Executing 3 thread name - mainExecuting 4 thread name - Thread-0Executing 4 thread name - mainExecuting 5 thread name - Thread-0Executing 5 thread name - mainExecuting 6 thread name - Thread-0Executing 6 thread name - mainExecuting 7 thread name - Thread-0Executing 7 thread name - mainExecuting 8 thread name - Thread-0Executing 8 thread name - mainExecuting 9 thread name - Thread-0Executing 9 thread name - mainExecuting 10 thread name - Thread-0Executing 10 thread name - main
4. Conclusion
In this article, You have seen how to create a thread without using Thread and Runnable.
Examples to create a thread using Anonymous Implementations.
As usual, All examples are over GitHub.
No comments:
Post a Comment
Please do not add any spam links in the comments section.