fork download
  1. import java.io.PrintStream;
  2.  
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.TimeUnit;
  6.  
  7. public final class Main {
  8.  
  9. private static void trySleep(final long period) {
  10. try {
  11. Thread.sleep(period);
  12. } catch (final InterruptedException ex) { }
  13. }
  14.  
  15. public static void main(final String[] argv) {
  16. final CountingTask task = new CountingTask();
  17. final ExecutorService executor = Executors.newSingleThreadExecutor();
  18. executor.execute(task);
  19.  
  20. trySleep(1000);
  21. System.out.println("trying to pause...");
  22. task.pause();
  23.  
  24. trySleep(1000);
  25. System.out.println("trying to resume...");
  26. task.resume();
  27.  
  28. executor.shutdown();
  29. try {
  30. executor.awaitTermination(5, TimeUnit.SECONDS);
  31. } catch (final InterruptedException ex) { }
  32. }
  33. }
  34.  
  35. final class CountingTask implements Runnable {
  36.  
  37. private volatile boolean paused;
  38.  
  39. @Override
  40. public void run() {
  41. final PrintStream out = System.out;
  42. try {
  43. out.println("counting starting");
  44. for (int i = 1; i <= 100; ++i) {
  45. out.printf("%3d ", i);
  46. if ((i % 10) == 0) {
  47. out.println();
  48. Thread.sleep(500);
  49. }
  50. if (paused) {
  51. out.println("counting pausing");
  52. synchronized (this) {
  53. wait();
  54. }
  55. }
  56. }
  57. out.println();
  58. } catch (Exception ex) {
  59. ex.printStackTrace();
  60. }
  61. }
  62.  
  63. public void pause() {
  64. paused = true;
  65. }
  66.  
  67. public void resume() {
  68. paused = false;
  69. synchronized (this) {
  70. notify();
  71. }
  72. }
  73. }
Success #stdin #stdout 0.08s 215936KB
stdin
Standard input is empty
stdout
counting starting
  1     2     3     4     5     6     7     8     9    10   
 11    12    13    14    15    16    17    18    19    20   
trying to pause...
counting pausing
trying to resume...
 21    22    23    24    25    26    27    28    29    30   
 31    32    33    34    35    36    37    38    39    40   
 41    42    43    44    45    46    47    48    49    50   
 51    52    53    54    55    56    57    58    59    60   
 61    62    63    64    65    66    67    68    69    70   
 71    72    73    74    75    76    77    78    79    80   
 81    82    83    84    85    86    87    88    89    90   
 91    92    93    94    95    96    97    98    99   100