

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


// A Thread subclass application public class SampleThread extends Thread { private int threadNum;
public SampleThread(int val){ threadNum = val; }//end of constructor
public void run( ){ System.out.println("Starting Thread Number: " + threadNum); try { Thread.sleep((long)(Math.random()*10000)); }catch (InterruptedException e) { } System.out.println("Stopping Thread Number: " + threadNum); }//end of run
public static void main (String [ ] args){ for (int i=0; i<5; i++){ Thread thr = new SampleThread(i); thr.start(); } }//end of main }//end of class definition
// A Runnable implementation public class SampleRunnable implements Runnable { private int threadNum;
public SampleRunnable(int val){ threadNum=val; }//end of constructor method
public void run(){ System.out.println("Starting Runnable Thread Number: " + threadNum);
try { Thread.sleep((long)(Math.random()*10000)); System.out.println("Completed sleep..now Waking up Thread Number: " + threadNum); }catch (InterruptedException e) { System.out.println("Interrupted Runnable Thread Number: "+ threadNum); }
}//end of run
public static void main (String [] args){ Thread [ ] thr = new Thread[5]; for (int i=0; i<5; i++){ Runnable srun = new SampleRunnable(i); //create a runnable object thr[i] = new Thread(srun); //create a thread using the runnable object thr[i].start(); int flag = (int) (Math.random()*3);
if (flag==0) thr[i].interrupt(); //interrupt thread }//end of for loop
}//end of main }//end of class definition
try { thr[4].join(); System.out.println("Main is out of here...."); }catch (InterruptedException e) { }
is inserted before the end of the main( ) method, the main thread will wait for the death of thread thr[4] before proceeding.