Created
March 8, 2017 04:16
-
-
Save toraj58/a24f8cb0bb2bface3e6cec39d02b3b65 to your computer and use it in GitHub Desktop.
Chat Multi-Thread Using wait and Notify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this template, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package waitnotifyexample; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
/** | |
* | |
* @author toraj | |
*/ | |
public class Main { | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// TODO code application logic here | |
System.out.println("startinggggggggggggggggggg"); | |
Chat m = new Chat(); | |
T1 t1 = new T1(m); | |
T2 t2 = new T2(m); | |
// try { | |
// t1.join(); | |
// t2.join(); | |
// | |
//// Thread.dumpStack(); | |
// } catch (InterruptedException ex) { | |
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); | |
// } | |
// System.out.println("end of main"); | |
// Thread.dumpStack(); | |
} | |
} | |
class Chat { | |
boolean flag = false; | |
public synchronized void Question(String msg) { | |
if (flag) { | |
try { | |
wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(msg); | |
flag = true; | |
notify(); | |
} | |
public synchronized void Answer(String msg) { | |
if (!flag) { | |
try { | |
wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(msg); | |
flag = false; | |
notify(); | |
} | |
} | |
class T1 extends Thread { | |
Chat m; | |
String[] s1 = { "Hiq", "How are you ?", "I am also doing fine!" }; | |
public T1(Chat m1) { | |
this.m = m1; | |
new Thread(this, "Question").start(); | |
} | |
public void run() { | |
for (int i = 0; i < s1.length; i++) { | |
m.Question(s1[i]); | |
} | |
// System.out.println("q finished"); | |
} | |
} | |
class T2 extends Thread { | |
Chat m; | |
String[] s2 = { "Hi", "I am good, what about you?", "Great!" }; | |
public T2(Chat m2) { | |
this.m = m2; | |
new Thread(this, "Answer").start(); | |
} | |
public void run() { | |
for (int i = 0; i < s2.length; i++) { | |
m.Answer(s2[i]); | |
} | |
// System.out.println("a finished"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment