Using AnonymousThread:

  1. package com.instanceofjava;
  2.  
  3. public class AnonymousThread
  4. {
  5.  
  6. public static void main(String[] args)
  7.     {
  8.         new Thread(){
  9.  
  10.             public void run(){
  11.  
  12.                 for (int i = 0; i  <=10; i++) {
  13.                    System.out.println("run"+i);
  14.                 }
  15.  
  16.             }
  17.  
  18.         }.start();
  19.  
  20.         for (int i = 0; i  <=10; i++) {
  21.             System.out.println("main:"+i);
  22.         }
  23. }
  24. }

Output:

  1. main:0
  2. run:0
  3. main:1
  4. run:1
  5. main:2
  6. run:2
  7. main:3
  8. run:3
  9. main:4
  10. run:4
  11. main:5
  12. run:5
  13. main:6
  14. run:6
  15. main:7
  16. run:7
  17. main:8
  18. run:8
  19. main:9
  20. run:9
  21. main:10
  22. run:10

 

Using AnonymousRunnable:

  1. package com.instanceofjava;
  2.  
  3. public class AnonymousRunnable
  4. {
  5.  
  6. public static void main(String[] args)
  7.     {
  8.         new Thread(new Runnable(){
  9.  
  10.  
  11.     public void run(){
  12.  
  13.                 for (int i = 0; i  <=10; i++) {
  14.                    System.out.println("run"+i);
  15.                 }
  16.  
  17.             }
  18.  }
  19. ).start();
  20.  
  21.         for (int i = 0; i  <=10; i++) {
  22.             System.out.println("main:"+i);
  23.         }
  24. }
  25. }


Output:

  1. main:0
  2. run0
  3. main:1
  4. run1
  5. main:2
  6. run2
  7. main:3
  8. run3
  9. main:4
  10. run4
  11. main:5
  12. run5
  13. main:6
  14. run6
  15. main:7
  16. run7
  17. main:8
  18. run8
  19. main:9
  20. run9
  21. main:10
  22. run10

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu