Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.dannil.mpt;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class Test {
- public Test() {
- }
- public void doOperation() {
- int topBoundary = 10000000;
- double beforeMillis;
- double afterMillis;
- System.out.println("Running in single-threaded mode");
- beforeMillis = System.currentTimeMillis();
- for (int i = 0; i < topBoundary; i++) {
- Prime.isPrime(i);
- }
- afterMillis = System.currentTimeMillis();
- System.out.println("Time elapsed: " + (afterMillis - beforeMillis) / 1000 + " sec.");
- System.gc();
- System.out.println("Running in multi-threaded mode");
- ExecutorService executor = Executors.newFixedThreadPool(4);
- beforeMillis = System.currentTimeMillis();
- for (int i = 0; i < topBoundary; i++) {
- Runnable worker = new PrimeWorker(i);
- executor.execute(worker);
- }
- executor.shutdown();
- afterMillis = System.currentTimeMillis();
- System.out.println("Time elapsed: " + (afterMillis - beforeMillis) / 1000 + " sec.");
- }
- class PrimeWorker implements Runnable {
- private int n;
- public PrimeWorker(int n) {
- this.n = n;
- }
- @Override
- public void run() {
- boolean isPrime = Prime.isPrime(this.n);
- if (isPrime) {
- // System.out.println(this.n + " is a prime number!");
- }
- }
- }
- public static void main(String[] args) {
- Test test = new Test();
- test.doOperation();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement