

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to java threads, explaining what they are, how they are started and stopped, and the difference between daemon and user threads. It also covers two methods of defining a multithreaded application: by instantiating a thread or implementing a runnable interface. Code examples for both approaches.
Typology: Study notes
1 / 2
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.