Consultor Eletrônico



Kbase 19838: Java Program to Test Threading
Autor   Progress Software Corporation - Progress
Acesso   Público
Publicação   24/11/2008
Status: Verified

GOAL:

Occasionally in debugging AdminServer or AppServer calls, messages pertaining to Java threads appear. The following test program confirms that the Java thread mechanism is working on your machine.

FIX:

Steps to run the test:
1) Save the code below as a file named "threadtester.java".
2) Set your path to include your Java compiler (javac).
3) javac threadtester.java
4) java threadtester

If everything works, you should see:
$ java threadtester
Starting threads
Threads started

thread3 reporting...
thread2 reporting...
thread1 reporting...
thread2 reporting...
thread3 reporting...
thread1 reporting...
thread1 reporting...
thread3 reporting...
thread1 reporting...
thread2 reporting...
thread1 reporting...
thread2 reporting...
thread3 reporting...
thread2 reporting...
thread3 reporting...

NOTE: The threads sleep for random intervals, and then announce
themselves, so the sequence above will vary. Each thread sleeps
five times, and announces itself after each sleep.

public class threadtester {
public static void main (String args[]) {
PrintThread thread1, thread2, thread3;

thread1 = new PrintThread("thread1");
thread2 = new PrintThread("thread2");
thread3 = new PrintThread("thread3");

System.err.println("\nStarting threads");

thread1.start();
thread2.start();
thread3.start();

System.err.println("Threads started\n");
}
}

class PrintThread extends Thread {
private int sleepTime;
private int i;

// PrintThread constructor assigns name to thread
// by calling Thread constructor
public PrintThread(String name) {
super(name);
}

// Execute the thread - sleep and wake five times.
public void run() {
for (i = 1; i <= 5; i++) {
// Put the thread to sleep for a random period
sleepTime = (int) (Math.random() * 5000);
try {
Thread.sleep(sleepTime);
}
catch (InterruptedException exception) {
System.err.println(exception.toString());
}
// Print the thread name
System.err.println(getName() + " reporting...");
}
}
}