Java Reference
In-Depth Information
Listing 6-61. A Test Class for the CallTracker Class
// CallTrackerTest.java
package com.jdojo.threads;
import java.util.Random;
public class CallTrackerTest {
public static void main(String[] args) {
// Let's start three threads to the CallTracker.call() method
new Thread(CallTrackerTest::run).start();
new Thread(CallTrackerTest::run).start();
new Thread(CallTrackerTest::run).start();
}
public static void run() {
Random random = new Random();
// Generate a random value between 1 and 5
int counter = random.nextInt(5) + 1;
// Print the thread name and teh generated random number by the thread
System.out.println(Thread.currentThread().getName() +
" generated counter: " + counter);
for (int i = 0; i < counter; i++) {
CallTracker.call();
}
}
}
(You may get a different output.)
Thread-0 generated counter: 4
Thread-1 generated counter: 2
Thread-2 generated counter: 3
Call counter for Thread-0 = 1
Call counter for Thread-2 = 1
Call counter for Thread-1 = 1
Call counter for Thread-2 = 2
Call counter for Thread-0 = 2
Call counter for Thread-2 = 3
Call counter for Thread-1 = 2
Call counter for Thread-0 = 3
Call counter for Thread-0 = 4
Search WWH ::




Custom Search