fork download
  1. //Implement Runnable Interface...
  2. class ImplementsRunnable implements Runnable {
  3.  
  4. private int counter = 0;
  5.  
  6. public void run() {
  7. counter++;
  8. System.out.println("ImplementsRunnable : Counter : " + counter);
  9. }
  10. }
  11.  
  12. //Extend Thread class...
  13. class ExtendsThread extends Thread {
  14.  
  15. private int counter = 0;
  16.  
  17. public void run() {
  18. counter++;
  19. System.out.println("ExtendsThread : Counter : " + counter);
  20. }
  21. }
  22.  
  23. //Use the above classes here in main to understand the differences more clearly...
  24. class ThreadVsRunnable {
  25.  
  26. public static void main(String args[]) throws Exception {
  27. // Multiple threads share the same object.
  28. ImplementsRunnable rc = new ImplementsRunnable();
  29. Thread t1 = new Thread(rc);
  30. t1.start();
  31. Thread.sleep(1000); // Waiting for 1 second before starting next thread
  32. Thread t2 = new Thread(rc);
  33. t2.start();
  34. Thread.sleep(1000); // Waiting for 1 second before starting next thread
  35. Thread t3 = new Thread(rc);
  36. t3.start();
  37.  
  38. // Creating new instance for every thread access.
  39. ExtendsThread tc1 = new ExtendsThread();
  40. Thread t11 = new Thread(tc1);
  41. t11.start();
  42. Thread.sleep(1000); // Waiting for 1 second before starting next thread
  43. Thread t21 = new Thread(tc1);
  44. t21.start();
  45. Thread.sleep(1000); // Waiting for 1 second before starting next thread
  46. Thread t31 = new Thread(tc1);
  47. t31.start();
  48. }
  49. }
Success #stdin #stdout 0.09s 34008KB
stdin
Standard input is empty
stdout
ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 2
ExtendsThread : Counter : 3