Advertisement
steverobinson

MultiThreading | Simple

Jul 11th, 2011
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3.  
  4. /**
  5. *A Simple Java program to explain basic MultiThreading.
  6. *@author Steve Robinson
  7. *@see footyntech.wordpress.com
  8. */
  9.  
  10.  
  11. class ThreadTest implements Runnable
  12. {
  13.     public int buffer=0;
  14.     public void run()
  15.     {
  16.         try
  17.         {
  18.             for(int i=0;i<50;i++)
  19.             {
  20.                 buffer+=i;
  21.                 Thread.sleep(400);
  22.             }
  23.         }
  24.         catch(InterruptedException e)
  25.         {
  26.             e.printStackTrace();
  27.         }
  28.         System.out.println("Child Thread Ended");
  29.     }
  30. }
  31.  
  32. class MultiThreading
  33. {
  34.     public static void main(String arg[])
  35.     {
  36.         ThreadTest temp=new ThreadTest();
  37.         Runnable r=temp;
  38.        
  39.         Thread thread=new Thread(r);
  40.         thread.start();
  41.        
  42.         String in;
  43.         Scanner input=new Scanner(System.in);
  44.        
  45.         System.out.println("Press \"p\" to print current value and \"q\" to quit.. ");
  46.         while(!((in=input.nextLine()).equals("q")))
  47.         {
  48.             if(in.equals("p"))
  49.             {  
  50.                     System.out.println("Current Value: " + temp.buffer);
  51.             }
  52.         }
  53.         System.out.println("Stopping Child Thread....\nExiting....");
  54.        
  55.         //Deprecated method. But completely safe for such small programs. Please ignore warnings...
  56.         thread.stop();  
  57.                
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement