- 전체
- JAVA 일반
- JAVA 수학
- JAVA 그래픽
- JAVA 자료구조
- JAVA 인공지능
- JAVA 인터넷
- Java Framework
- Java GUI (AWT,SWING,SWT,JFACE)
- SWT and RCP (web RAP/RWT)[eclipse], EMF
JAVA 일반 Java - Interthread Communication
2015.07.15 21:01
Java - Interthread Communication
http://www.tutorialspoint.com/java/java_thread_communication.htmIf you are aware of interprocess communication then it will be easy for you to understand inter thread communication. Inter thread communication is important when you develop an application where two or more threads exchange some information.
There are simply three methods and a little trick which makes thread communication possible. First let's see all the three methods listed below:
| SN | Methods with Description |
|---|---|
| 1 | public void wait Causes the current thread to wait until another thread invokes the notify |
| 2 | public void notify Wakes up a single thread that is waiting on this object's monitor. |
| 3 | public void notifyAll Wakes up all the threads that called wait |
These methods have been implemented as final methods in Object, so they are available in all the classes. All three methods can be called only from within a synchronized context.
Example:
This examples shows how two thread can communicate using wait
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 implements Runnable { Chat m; String[] s1 = { "Hi", "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]); } } } class T2 implements Runnable { 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]); } } } public class TestThread { public static void main(String[] args) { Chat m = new Chat(); new T1(m); new T2(m); } }
When above program is complied and executed, it produces following result:
Hi Hi How are you ? I am good, what about you? I am also doing fine! Great!
Above example has been taken and then modified from [http://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.

