Launching and interrupting a thread example

From MyWiki
Jump to: navigation, search
public class SleepMessages implements Runnable {
static	int a = 0;
			    public void run() {
					try{
                                  System.out.println("Hello from a thread! a is "+a);
                                  Thread.sleep(6000);
                                  System.out.println("Hello from a thread! a is "+a);
                                  Thread.sleep(6000);
                                  System.out.println("Hello from a thread! a is "+a);
                        }
                        catch(Exception e){}
	                              }
 
    public static void main(String args[]) throws InterruptedException
    {
		//(new Thread(new SleepMessages())).start();
		SleepMessages sm = new SleepMessages();
		Thread th = new Thread(sm);
		th.start();
 
 
        String importantInfo[] = {
                                 "Mares eat oats",
                                 "Does eat oats",
                                 "Little lambs eat ivy",
                                 "A kid will eat ivy too"
                                 };
 
        for (int i = 0;i < importantInfo.length;i++) {
                                                      //Pause for 4 seconds
                                                      Thread.sleep(4000);
                                                      th.interrupt();
                                                      //Print a message
                                                      a = 4;
                                                      System.out.println(importantInfo[i]);
                                                      }
    }
}