Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.*;
- class Test implements Runnable {
- static int numberOfThreads;
- static CyclicBarrier barrier;
- public static void main(String[] args) throws InterruptedException {
- // TEST WITH 4 THREADS
- numberOfThreads = 4;
- barrier = new CyclicBarrier(numberOfThreads);
- long start = System.currentTimeMillis();
- Test t = new Test();
- Thread[] threads = new Thread[numberOfThreads];
- for (int i = 0; i < numberOfThreads; i++)
- (threads[i] = new Thread(t)).start();
- for (Thread thread : threads)
- thread.join();
- System.out.println("4 threads: " + (System.currentTimeMillis() - start));
- // TEST WITH 1 THREAD
- numberOfThreads = 1;
- barrier = new CyclicBarrier(numberOfThreads);
- start = System.currentTimeMillis();
- t = new Test();
- threads = new Thread[numberOfThreads];
- for (int i = 0; i < numberOfThreads; i++)
- (threads[i] = new Thread(t)).start();
- for (Thread thread : threads)
- thread.join();
- System.out.println("1 thread: " + (System.currentTimeMillis() - start));
- }
- public void run() {
- int i = 0;
- while (i++ < 5) {
- try {
- // perform an ammount of computations inversely proportional to
- // the number of threads.
- for (int j = 0; j < 10000 / numberOfThreads; j++)
- countPrimes();
- barrier.await(); // CyclicBarrier waiting for all threads
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public void countPrimes() {
- int i = 0;
- int primeNumberCounter = 0;
- while (++i <= 1000) {
- int i1 = (int) Math.ceil(Math.sqrt(i));
- boolean isPrimeNumber = false;
- while (i1 > 1) {
- if ((i != i1) && (i % i1 == 0)) {
- isPrimeNumber = false;
- break;
- } else if (!isPrimeNumber) {
- isPrimeNumber = true;
- }
- --i1;
- }
- if (isPrimeNumber)
- ++primeNumberCounter;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment