Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package stringcompareemp;
  7.  
  8. class Chat {
  9.  
  10. boolean flag = false;
  11.  
  12. public synchronized void Question(String msg) {
  13. if (flag) {
  14. try {
  15. wait(2000,300);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. System.out.println(msg);
  21. flag = true;
  22. notifyAll();
  23. }
  24.  
  25. public synchronized void Answer(String msg) {
  26. if (!flag) {
  27. try {
  28. wait(5000,300);
  29. } catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. System.out.println(msg);
  34. flag = false;
  35. notify();
  36. }
  37. }
  38.  
  39. class T1 implements Runnable {
  40.  
  41. Chat m;
  42. String[] s1 = {"Hi", "How are you ?", "I am also doing fine!","ahihi","ahihii"};
  43.  
  44. public T1(Chat m1) {
  45. this.m = m1;
  46. new Thread(this, "Question").start();
  47. }
  48.  
  49. public void run() {
  50. for (int i = 0; i < s1.length; i++) {
  51. m.Question(s1[i]);
  52. }
  53. }
  54. }
  55.  
  56. class T2 implements Runnable {
  57.  
  58. Chat m;
  59. String[] s2 = {"Hi", "I am good, what about you?", "Great!"};
  60.  
  61. public T2(Chat m2) {
  62. this.m = m2;
  63. new Thread(this, "Answer").start();
  64. }
  65.  
  66. public void run() {
  67. for (int i = 0; i < s2.length; i++) {
  68. m.Answer(s2[i]);
  69. }
  70. }
  71. }
  72.  
  73. public class TestThread {
  74.  
  75. public static void main(String[] args) {
  76. Chat m = new Chat();
  77. new T1(m);
  78. new T2(m);
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement