Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ThreadTest {
- static int test = 0;
- public static void main(final String[] arguments) throws InterruptedException {
- doStuff();
- System.out.println(test);
- }
- public static boolean doStuff() {
- int threadCount = Runtime.getRuntime().availableProcessors();
- ExecutorService executor = Executors.newFixedThreadPool(threadCount);
- ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
- for (int i = 0; i < threadCount; i++) {
- executor.submit(new Task());
- }
- executor.shutdown();
- return(true);
- }
- static class Task implements Runnable {
- static Boolean found = false;
- static String test = "";
- public Task() {
- }
- public void run() {
- Random ran = new Random();
- while (!found) {
- if (ran.nextInt(1000000000 - 1) + 1 == 10) {
- System.out.println("Thread : " + Thread.currentThread().getName() + " found it");
- synchronized (found) {
- found = true;
- setResult(10);
- }
- }
- }
- }
- }
- public static synchronized void setResult(int result) {
- test = result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement