Advertisement
Guest User

Untitled

a guest
Dec 18th, 2014
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. public class NewThread extends Thread {
  2. private String name;
  3. private Thread thread;
  4. private boolean suspendFlag;
  5. NewThread(String name) {
  6. this.name = name;
  7. this.thread = new Thread(this, name);
  8. this.suspendFlag = false;
  9. this.thread.start();
  10. }
  11. public void run() {
  12. try {
  13. for (int i = 0; i < 10; ++i) {
  14. System.out.println(name + " => ЗДРАВО!");
  15. Thread.sleep(1000);
  16. synchronized (this) {
  17. while (suspendFlag) {
  18. this.wait();
  19. }
  20. }
  21. }
  22. } catch (InterruptedException e) {
  23. System.err.println(e);
  24. }
  25. System.out.println(name + " => ЗАВРШИВ!");
  26. }public void mySuspend() {
  27. this.suspendFlag = true;
  28. }
  29. public synchronized void myResume() {
  30. this.suspendFlag = false;
  31. this.notify();
  32. }
  33. public static void main(String args[]) {
  34. NewThread thread1 = new NewThread("Нишка 1");
  35. NewThread thread2 = new NewThread("Нишка 2");
  36. NewThread thread3 = new NewThread("Нишка 3");
  37. try {
  38. Thread.sleep(3000);
  39. System.out.println("Ја стопираме нишката 1!");
  40. thread1.mySuspend();
  41. System.out.println("Ја стопираме нишката 2!");
  42. thread2.mySuspend();
  43. Thread.sleep(6000);
  44. System.out.println("Нишката 1 продолжи со работа!");
  45. thread1.myResume();
  46. System.out.println("Нишката 2 продолжи со работа!");
  47. thread2.myResume();
  48. System.out.println("Ја стопираме нишката 3!");
  49. thread3.mySuspend();
  50. Thread.sleep(3000);
  51. System.out.println("Нишката 3 продолжи со работа!");
  52. thread3.myResume();
  53. thread1.join();
  54. thread2.join();
  55. thread3.join();
  56. } catch (InterruptedException e) {
  57. System.err.println(e);
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement