Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2018
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. public class ThreadTest {
  2.  
  3.     static int test = 0;
  4.  
  5.     public static void main(final String[] arguments) throws InterruptedException {
  6.         doStuff();
  7.         System.out.println(test);
  8.     }
  9.  
  10.     public static boolean doStuff() {
  11.         int threadCount = Runtime.getRuntime().availableProcessors();
  12.         ExecutorService executor = Executors.newFixedThreadPool(threadCount);
  13.         ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
  14.         for (int i = 0; i < threadCount; i++) {
  15.             executor.submit(new Task());
  16.         }
  17.  
  18.         executor.shutdown();
  19.         return(true);
  20.     }
  21.  
  22.     static class Task implements Runnable {
  23.  
  24.         static Boolean found = false;
  25.         static String test = "";
  26.  
  27.         public Task() {
  28.  
  29.         }
  30.  
  31.         public void run() {
  32.             Random ran = new Random();
  33.             while (!found) {
  34.                 if (ran.nextInt(1000000000 - 1) + 1 == 10) {
  35.                     System.out.println("Thread : " + Thread.currentThread().getName() + " found it");
  36.                     synchronized (found) {
  37.                         found = true;
  38.                         setResult(10);
  39.                     }
  40.                 }
  41.             }
  42.         }
  43.     }
  44.  
  45.     public static synchronized void setResult(int result) {
  46.         test = result;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement