Created
March 14, 2013 17:17
-
-
Save tyrcho/5163243 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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(); | |
} | |
} |
This file contains hidden or 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
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