Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Created March 14, 2013 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyrcho/5163243 to your computer and use it in GitHub Desktop.
Save tyrcho/5163243 to your computer and use it in GitHub Desktop.
public class SingleThreadDemo {
public static void infiniteLoop() {
while (true) {
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
System.out.println("started");
infiniteLoop();
}
};
t.start();
t.join(1000);
System.out.println("after join");
t.stop();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ThreadPoolDemo {
public static void infiniteLoop() {
while (true) {
Thread.yield();
}
}
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(2);
Callable<String> task = new Callable<String>() {
public String call() throws Exception {
System.out.println("starting task");
infiniteLoop();
System.out.println("ending task");
return "Ready!";
}
};
Future<String> future = null;
for (int i = 0; i < 4; i++) {
future = executor.submit(task);
}
try {
System.out.println("Started..");
System.out.println(future.get(1, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Timeout!");
}
executor.shutdownNow();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment