Java-thread-communication
提供:Dev Guides
Java-スレッド間通信
プロセス間通信を知っている場合、スレッド間通信を理解するのは簡単です。 スレッド間通信は、2つ以上のスレッドが何らかの情報を交換するアプリケーションを開発するときに重要です。
3つの簡単なメソッドと、スレッド通信を可能にする小さなトリックがあります。 3つの方法はすべて以下にリストされています-
Sr.No. | Method & Description |
---|---|
1 |
public void wait() 別のスレッドがnotify()を呼び出すまで、現在のスレッドを待機させます。 |
2 |
public void notify() このオブジェクトのモニターで待機している単一のスレッドを起動します。 |
3 |
public void notifyAll() 同じオブジェクトでwait()を呼び出したすべてのスレッドを起動します。 |
これらのメソッドはObjectの final メソッドとして実装されているため、すべてのクラスで使用できます。 3つのメソッドはすべて、 synchronized コンテキスト内からのみ呼び出すことができます。
例
この例は、2つのスレッドが* wait()および notify()*メソッドを使用して通信する方法を示しています。 同じ概念を使用して、複雑なシステムを作成できます。
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);
}
}
上記のプログラムがコンパイルされて実行されると、次の結果が生成されます-
Hi
Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
上記の例が取られ、[https://stackoverflow.com/questions/2170520/inter-thread-communication-in-java]から変更されました