Posted By

edwarddr on 05/19/12


Tagged

problem quiz


Versions (?)

runningSum


 / Published in: Java
 

It's a piece of code that calculate the sum from a sequence of number that inserted into the program in a certain duration. This is an example of using multiple threads.

  1. import java.util.Date.*;
  2. import java.util.ArrayList;
  3.  
  4. class runningSum implements Runnable
  5. {
  6. private String str;
  7. private int sum;
  8. private ArrayList<Integer> numSequence;
  9. private int currentSum;
  10. public boolean terminates;
  11. private long timeRecord;
  12. private int partialSum;
  13.  
  14. public runningSum()
  15. {
  16. //str=new String (s);
  17. numSequence = new ArrayList<Integer>();
  18. timeRecord = System.currentTimeMillis();
  19. terminates = false;
  20. sum = 0;
  21. partialSum = 0;
  22. }
  23.  
  24.  
  25. public void add(int a)
  26. {
  27. partialSum = partialSum + a;
  28. }
  29.  
  30. public int retrieveV()
  31. {
  32. long newTimes = System.currentTimeMillis();
  33. if (newTimes - timeRecord > 300000)
  34. {
  35. return sum;
  36. }else
  37. {
  38. return sum + partialSum;
  39. }
  40. }
  41.  
  42. public void run ()
  43. {
  44. for (;;)
  45. {
  46. if (terminates)
  47. {
  48. break;
  49. }
  50. try
  51. {
  52. Thread.sleep(5000);
  53. synchronized (this) {
  54. System.out.println("Sum before: " + sum + ", partial before: " + partialSum + ", millis: " + System.currentTimeMillis());
  55. sum = sum + partialSum;
  56. numSequence.add(new Integer(partialSum));
  57. partialSum = 0;
  58. while (numSequence.size() > 60)
  59. {
  60. Integer toRemove = (Integer) numSequence.remove(0);
  61. int temp = toRemove.intValue();
  62. sum = sum - temp;
  63.  
  64. }
  65. }
  66. }catch(Exception e)
  67. {
  68. System.out.println("Woops:" + e.getMessage());
  69. }
  70. }
  71. System.out.print ("Finished...");
  72. }
  73.  
  74. public static void main(String args[])
  75. {
  76. try{
  77. runningSum sumA = new runningSum();
  78. (new Thread(sumA)).start();
  79. for (int i = 0; i < 100; i++)
  80. {
  81. sumA.add(100);
  82. Thread.sleep(15000);
  83. System.out.println("Sum is:" + sumA.retrieveV() + ", millis: " + System.currentTimeMillis());
  84. }
  85. sumA.terminates = true;
  86. }catch(Exception e)
  87. {
  88. System.out.println("Woops");
  89. }
  90. }
  91. }

Report this snippet  

You need to login to post a comment.