Perform the following steps to implement the example:
- Create a class named Task that implements the Runnable interface:
public class Task implements Runnable {
- Implement the run() method of the task:
@Override
public void run() {
- Create a loop with 100 steps:
for (int i=0; i<100; i++) {
- In each step, put the thread to sleep for 100 milliseconds:
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
- 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);
}
}
}
- 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{
- Create a Task object named task:
Task task = new Task();
- Create a Thread array with five elements:
Thread threads[] = new Thread[5];
- 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();
}
- 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++) {
- 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: ");
- 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("********************** ");
}
- Put the thread to sleep for one second and close the loop and the class:
TimeUnit.SECONDS.sleep(1);
}
}
}