Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. public class CounterOfSpace {
  2. private int counterOfSpaces;
  3. private int counterOfWords;
  4. private String text;
  5. private Thread thread01;
  6. private Thread thread02;
  7.  
  8. public CounterOfSpace(String text) {
  9. this.text = text;
  10. }
  11.  
  12. void startAll() {
  13. System.out.println("Start program");
  14.  
  15. calcWords();
  16. calcSpaces();
  17. stopThreads();
  18. thread01.start();
  19. thread02.start();
  20. try {
  21. thread01.join();
  22. thread02.join();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26.  
  27. System.out.println("Finish program");
  28. }
  29.  
  30. private void calcSpaces() {
  31. thread01 = new Thread(new Runnable() {
  32. @Override
  33. public void run() {
  34. if (text.length() == 0) return;
  35. for (char c : text.toCharArray()) {
  36. if (c == ' ') {
  37. counterOfSpaces++;
  38. System.out.println("counterOfSpaces "+counterOfSpaces);
  39. }
  40. }
  41. }
  42. });
  43. }
  44.  
  45. private void calcWords() {
  46. thread02 = new Thread(new Runnable() {
  47. @Override
  48. public void run() {
  49. if (text.length() == 0) return;
  50. String[] words = text.split(" ");
  51. for (String word : words) {
  52. if (!word.equals(" ")) {
  53. counterOfWords++;
  54. System.out.println("counterOfWords "+counterOfWords);
  55. }
  56. }
  57. }
  58. });
  59. }
  60.  
  61. private void stopThreads() {
  62. ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
  63. Future handler1 = executor.submit(thread01);
  64. Future handler2 = executor.submit(thread02);
  65. Runnable r = new Runnable() {
  66. @Override
  67. public void run() {
  68. handler1.cancel(true);
  69. handler2.cancel(true);
  70. }
  71. };
  72. executor.schedule(r, 3, TimeUnit.MILLISECONDS);
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement