Java Reference
In-Depth Information
Just became this:
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.err.println("Exception in " + t + ": " + e);
}
);
The code for this entire implementation is given in Listing 6-2.
Listing 6-2. Using Lambdas to Define Thread Instances
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Listing2 {
private static void joinThread(Thread t) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void printPrimes(int maxBitLength) {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.err.println("Exception in " + t + ": " + e);
}
);
int processorCount = Runtime.getRuntime().availableProcessors();
BlockingQueue<String> primes = new LinkedBlockingQueue<String>();
Thread[] threads = new Thread[processorCount];
for (int t = 0; t < threads.length; t++) {
int modulus = t;
threads[modulus] = new Thread(() -> {
for (int i = 0; i < maxBitLength; i++) {
int bitLength = i + 1;
if (bitLength % processorCount == modulus) {
BigInteger prime = PrimeFactory.ofLength(bitLength);
primes.add(prime.toString());
}
}
}
);
threads[modulus].start();
}
Search WWH ::




Custom Search