Monday, June 19, 2017

Java Thread Example

In this example, Five Threads are being invoked which takes input as Integer and prepare table. Also, Used some of methods like Sleep and isInterrupted to understand its uses.

package test;
/**
 * MyThread2 class which creates thread by extending Thread Class
 * @author Nitesh.Gupta
 */
public class MyThread2 extends Thread {
/**
* Initializing count with 1
*/
private int count=1;
/**
* MyThread constructor which takes an input and assign it to class level variable
* @param count
*/
MyThread2 (int count){
this.count = count;
}
/**
* Run method which gets executed as soon as thread.run called.
*/
@Override
public void run() {
calculateTable();
}
/**
* Helper method for calucalting table
*/
private void calculateTable() {
System.out.println("Thread started:::"+Thread.currentThread().getName());
for (int i=1; i<=10 ; i++){
int counting = i * count;
System.out.println("Table of " + i + " Prepared by Thread "+this.getId() +" Name "+this.getName());
System.out.println("Count of " + count + "*" + i + "=" +counting);
}
}
public static void main (String str[]) throws InterruptedException{
for (int k=1; k<5 font="" k="">
Thread.sleep(1000);
MyThread2 t1 = new MyThread2(k);
t1.start();
//IsInterrupted method to check if thread is interrupted in between or not
if (t1.isInterrupted()){
throw new InterruptedException();
}
}
}
}

No comments:

Post a Comment