How to do it...

Perform the following steps to implement the example:

  1. Create a class named Task that implements the Runnable interface:
        public class Task implements Runnable { 
  1. Implement the run() method of the task:
        @Override 
public void run() {
  1. Create a loop with 100 steps:
        for (int i=0; i<100; i++) { 
  1. In each step, put the thread to sleep for 100 milliseconds:
        try { 
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
  1. Write a message in the console with the name of the thread and the step number:
              System.out.printf("%s: %d
",Thread.currentThread()
.getName(),i);
}
}
}
  1. Create the main class of the example. Create a class named Main with a main() method:
        public class Main { 
public static void main(String[] args) throws Exception{
  1. Create a Task object named task:
        Task task = new Task(); 
  1. Create a Thread array with five elements:
        Thread threads[] = new Thread[5]; 
  1. Create and start five threads to execute the Task object created earlier:
        for (int i = 0; i < 5; i++) { 
threads[i] = new Thread(task);
threads[i].setPriority(i + 1);
threads[i].start();
}
  1. Create a loop with ten steps to write information about the threads launched before. Inside it, create another loop with five steps:
        for (int j = 0; j < 10; j++) { 
System.out.printf("Main: Logging threads ");
for (int i = 0; i < threads.length; i++) {
  1. For each thread, write its name, its status, its group, and the length of its stack trace in the console:
        System.out.printf("**********************
"); 
System.out.printf("Main: %d: Id: %d Name: %s: Priority: %d ",i,
threads[i].getId(),threads[i].getName(),
threads[i].getPriority());
System.out.printf("Main: Status: %s ",threads[i].getState());
System.out.printf("Main: Thread Group: %s ",
threads[i].getThreadGroup());
System.out.printf("Main: Stack Trace: ");
  1. Write a loop to write the stack trace of the thread:
          for (int t=0; t<threads[i].getStackTrace().length; t++) { 
System.out.printf("Main: %s ",threads[i].getStackTrace()
[t]);
}
System.out.printf("********************** ");
}
  1. Put the thread to sleep for one second and close the loop and the class:
              TimeUnit.SECONDS.sleep(1); 
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.79