fork download
  1.  
  2. import java.io.PrintStream;
  3. import java.util.*;
  4. import java.util.concurrent.*;
  5.  
  6. public class Main
  7. {
  8. static PrintStream o=System.out;
  9. public static
  10. void main(String[] args)
  11. throws Exception
  12. {
  13. Future f=execute ( 1,TimeUnit.SECONDS, new Callable (){
  14.  
  15. @Override
  16. public Object call ()
  17. throws Exception
  18. {
  19. for(int i=0;;++i)
  20. if (i % 100000000==0)
  21. o.println ( "working hard..." );
  22. }
  23. });
  24. o.println ( "Cancel!" );
  25. f.cancel ( false ); //ты больше не нужен
  26. f.cancel ( true ); //да останавливайся сука
  27. executor.shutdownNow (); //ну пожалуйста - освободи ценные ресурсы
  28. o.println ( "Shutdown" );
  29.  
  30. }
  31. @SuppressWarnings("unchecked")
  32. public static <T>
  33. Future<T> execute(
  34. long timeout,TimeUnit unit, Callable<T> task
  35. ){
  36. return executeAll(timeout,unit,Arrays.asList ( task)).get(0);
  37. }
  38.  
  39. public static <T>
  40. List<Future<T>> executeAll(
  41. long timeout, TimeUnit unit,Collection<Callable<T>> tasks
  42. ){
  43. try{
  44. return executor.invokeAll(tasks, timeout, unit);
  45. throw new RuntimeException(e);
  46. }
  47. }
  48. static void sl(int millis){
  49. try {
  50. Thread.sleep (millis);
  51. }catch (InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. final static ExecutorService
  56. executor = Executors.newFixedThreadPool ( 3 );
  57. }
  58.  
Runtime error #stdin #stdout 4.99s 246016KB
stdin
Standard input is empty
stdout
working hard...
Cancel!
Shutdown
working hard...
working hard...