Advertisement
Maruf_Hasan

Creating Thread Using Interface

Sep 20th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1.  
  2. class thread implements Runnable
  3. {
  4. Thread t;
  5. thread()//constructor for initializing the class
  6. {
  7. t=new Thread(this,"Demo");//intialializing this thread using this..
  8. System.out.println("Child Thread ");
  9. t.start();//starting the thread by calling start() function.it calls the run function
  10. }
  11. public void run()
  12. {
  13. try
  14. {
  15. for(int i=0;i<10;i++)
  16. {
  17. System.out.println("Fuck All");
  18. Thread.sleep(500);//interruption of 500 ms
  19. }
  20. }catch(InterruptedException e)//sleep method can throw exception.to handle this exception
  21. {
  22. System.out.println("Child Thread interrupted");
  23. }
  24. System.out.println("Exiting Child Thread");
  25. }
  26.  
  27. }
  28. public class NewThread {
  29. public static void main(String args[])
  30. {
  31. new thread();
  32. try
  33. {
  34. for(int i=0;i<10;i++)
  35. {
  36. System.out.println("Main Thread "+i);
  37. Thread.sleep(1000);//same as before
  38. }
  39. }catch(InterruptedException e)
  40. {
  41. System.out.println("Main Thread Interrupted");
  42. }
  43. System.out.println("Main thread Exiting");
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement