Advertisement
iccaka

Java Multithreading example.

Aug 22nd, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.concurrent.*;
  3.  
  4. public class Test {
  5.  
  6.     public static void main(String[] args) throws ExecutionException, InterruptedException {
  7.  
  8.         List<Integer> list = new ArrayList<>();  // Main list
  9.        
  10.         list.addAll(Arrays.asList(23,45,1,3,56,6,123,55,3,1,5,6,1,3,6,3,1,35,6,3,1,35,8,689,56,-1));  // Fill it up with some numbers
  11.  
  12.         ExecutorService es = Executors.newFixedThreadPool(10);  // Make a fixed thread pool
  13.         Future<Boolean>[] futures = new Future[list.size()];  // We will store the results here
  14.  
  15.         for (int i = 0; i < list.size(); i++) {
  16.             int currInt = i;
  17.             futures[i] = es.submit(() -> isBiggest(list, list.get(currInt)));  // Execute a new Callable, passing the list and the current integer
  18.  
  19.             if (futures[i].get()){  // If the number is the biggest one...
  20.                 System.out.println(list.get(currInt));  // print it...
  21.                 es.awaitTermination(500, TimeUnit.MILLISECONDS);  // wait for every thread to terminate...
  22.                 es.shutdown();  // and finally shut down everything
  23.                 break;  // Exit from the for loop
  24.             }
  25.         }
  26.  
  27.     }
  28.  
  29.     private static boolean isBiggest(List<Integer> list, Integer integer) {
  30.         list.sort(Comparator.naturalOrder());  // Sort the list
  31.  
  32.         if(list.get(list.size() - 1) > integer){  // get the highest value and check if it is bigger than the passed integer
  33.             return false;
  34.         }
  35.  
  36.         return true;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement