まず、複数のスレッド間の通信は何ですか
1.コンセプト:複数のスレッドは、実際には複数のスレッド、同じリソースを操作するが、異なる移動操作との間の通信。
第二に、マルチスレッド通信は、シミュレーションの問題を新興
1.需要:最初のスレッドの書き込み(入力)ユーザーは、別のスレッドテイクが読み取り、書き込み操作を実現するために、ユーザを(アウト)をお読みください。
2.コード
// 共享对象
class Res {
// 姓名
public String name;
// 性别
public String sex;
}
// 生产这线程
class IntThread extends Thread {
public Res res;
public IntThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0; // 1
while (true) {
if (count == 0) {
res.name = "小红";
res.sex = "女";
} else {
res.name = "小明";
res.sex = "男";
}
count = (count + 1) % 2;// 0 1 0 1 0 1
}
}
}
// 读取线程
class OutThread extends Thread {
public Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
System.out.println(res.name + "," + res.sex);
}
}
}
public class Test0001 {
public static void main(String[] args) throws InterruptedException {
Res res = new Res();
IntThread intThread = new IntThread(res);
OutThread outThread = new OutThread(res);
intThread.start();
outThread.start();
}
}
3.結果
注:データは、スレッド安全性の問題を引き起こして、混同されていません
この問題を解決するための第三に、マルチスレッド化通信シミュレーション
1.コード
// 共享对象
class Res {
// 姓名
public String name;
// 性别
public String sex;
// 为true情况下 允许读,不能写
// 为false情况下 允许写,不能读。
public boolean flag = false;
}
// 生产这线程
class IntThread extends Thread {
public Res res;
public IntThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0; // 1
while (true) {
synchronized (res) {
if (res.flag) {
try {
res.wait();// 釋放当前锁对象
} catch (Exception e) {
// TODO: handle exception
}
}
if (count == 0) {
res.name = "小红";
res.sex = "女";
} else {
res.name = "小明";
res.sex = "男";
}
count = (count + 1) % 2;// 0 1 0 1 0 1
res.flag = true;// 标记当前线程为等待
res.notify();// 唤醒被等待的线程
}
}
}
}
// 读取线程
class OutThread extends Thread {
public Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
try {
if (!res.flag) {
res.wait();
}
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(res.name + "," + res.sex);
res.flag = false;
res.notify();
}
}
}
}
public class Test0001 {
public synchronized static void main(String[] args) throws InterruptedException {
Res res = new Res();
IntThread intThread = new IntThread(res);
OutThread outThread = new OutThread(res);
intThread.start();
outThread.start();
}
}
2.結果
3.分析します
それは、オブジェクトのロックを必要とするので3.1。、彼らは同期の使用に配置する必要があります。待って、同期の内側を使用してください通知します。
3.2.Wait必須の暫定的なスレッドは、現在、他のスレッドが実行する機会を持つことができるようにすることを、実行、およびリソースのロックを解除されます。
注:スレッドの同期を使用してください、と同じロックリソースです
第四に、小さな福祉
差分1.waitを眠ります
睡眠()メソッドのために、我々は最初のThreadクラスを属するかを知る必要があります。そして、待機()メソッドは、オブジェクトクラスに属します。
睡眠()メソッドは、指定した時間を停止するプログラムでの結果なので、他のスレッドのCPUということはなく、指定した時間がアップしているとき、彼の遺骨は、状態を監視して、自動的に運転を再開します。
睡眠()メソッドの呼び出し中に、スレッドがオブジェクトのロックを解除しません。
そして、するとき、コール待ち()メソッドは、スレッドは、操作にオブジェクトのロックを取得するオブジェクトのロックプールの準備ができて移動する前に)のみ(このオブジェクトの通知呼び出した後、ロックプールを待つために、このオブジェクトの待機に、スレッドのメソッドをオブジェクトのロックを放棄します。
第五に、の終わり
常に信念を貫きます!!!