-
-
Save anonymous/1e8de4e6a5d112cc8815 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.creatures.util; | |
import java.util.concurrent.*; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* @author Septron | |
* @since February, 28 | |
*/ | |
public class Pool { | |
public static Pool singleton; | |
static { | |
singleton = new Pool(); | |
} | |
private final ThreadFactory factory = new ThreadFactory() { | |
private final AtomicInteger count = new AtomicInteger(); | |
@Override | |
public Thread newThread(Runnable r) { | |
Thread thread = new Thread(r); | |
thread.setName(String.format("Worker-%d", count.getAndIncrement())); | |
return thread; | |
} | |
}; | |
public final ExecutorService executor = Executors.newCachedThreadPool(factory); | |
} | |
class Example implements Callable<Boolean> { | |
public static void main(String... args) throws Exception { | |
Future<Boolean> a = Pool.singleton.executor.submit(new Example(true)); | |
// Do other stuff | |
// ... | |
// Gets the value of the submitted method... (Will wait if it needs to) | |
if (a.get()) { | |
System.out.println("Hello world from thread " + Thread.currentThread().getName()); | |
} | |
Pool.singleton.executor.shutdown(); | |
} | |
private final boolean stuff; | |
public Example(final boolean stuff) { | |
this.stuff = stuff; | |
} | |
@Override | |
public Boolean call() throws Exception { | |
System.out.println("Hello world from thread " + Thread.currentThread().getName()); | |
return stuff; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment