code_junkie

Can classes in java that implement runnable have methods other than run()

Nov 14th, 2011
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. public static void main(String args[])
  2. {
  3. try
  4. {
  5. myClass test = new Thread(new myClass(stuff));
  6. test.start();
  7. test.join();
  8. }
  9. catch (Throwable t) { }
  10. }
  11.  
  12. Thread test = new Thread(new myClass(stuff));
  13. teste.start();
  14. teste.join();
  15.  
  16. public class MyRunner implements Runnable
  17. {
  18. @Override public void run();
  19. public void somethingElse();
  20. }
  21.  
  22. Runnable r = new MyRunner();
  23. r.somethingElse(); // won't work, this method not defined by Runnable.
  24.  
  25. MyRunner m = new MyRunner();
  26. m.somethingElse(); // success!
  27.  
  28. class MyRunnable implements Runnable() {
  29. public void run() { /* do run stuff */ }
  30. public void print() { /* do print stuff */ }
  31. }
  32.  
  33. class MyThread extends Thread() {
  34. public void run() { /* do run stuff */ }
  35. public void print() { /* do print stuff */ }
  36. }
  37.  
  38. Thread t = new Thread(new MyRunnable());
  39. t.start();
  40. t.print(); // error, t is a Thread not a MyRunnable and not a MyThread
  41. t.join();
  42.  
  43. MyRunnable mr = new MyRunnable();
  44. mr.run(); // doesn't run in its own thread
  45. mr.print(); // this is ok
  46.  
  47. Runnable r = new MyRunnable();
  48. r.run(); // doesn't run in its own thread
  49. r.print(); // error, r is defined as Runnable which has no print() method
  50.  
  51. MyThread mt = new MyThread();
  52. mt.start();
  53. mt.print(); // this is ok because mt is a MyThread
  54. mt.join();
  55.  
  56. myClass test = new Thread(new myClass(stuff));
  57.  
  58. Thread test = new Thread(new myClass(stuff));
  59.  
  60. public static void main(String args[])
  61. {
  62. try
  63. {
  64. myClass foo = new myClass(stuff);
  65. myClass test = new Thread(foo);
  66. test.start();
  67. test.join();
  68. foo.print();
  69. }
  70. catch (Throwable t) { }
  71. }
Add Comment
Please, Sign In to add comment