解决线程间通信的安全问题:同步锁的使用:
添加同步锁后,问题解决:
package com.zzl.thread;
/**
* 线程间通讯
* 所谓线程间通讯,即多个线程操作同一资源,但是操作的动作不同。
*
*/
class Resource{
String name;
String sex;
}
class InRunnable implements Runnable{
private Resource r;
public InRunnable(Resource r){
this.r = r;
}
@Override
public void run() {
int x = 0;
while(true){
synchronized(r){
if(x == 0){
r.name = "mike";
r.sex = "man";
}else{
r.name = "胖胖胖胖胖胖胖胖";
r.sex = "女女女女女女";
}
x = (x+1)%2;
}
}
}
}
class OutRunnable implements Runnable{
private Resource r;
public OutRunnable(Resource r){
this.r = r;
}
@Override
public void run() {
while(true){
synchronized(r){
System.out.println(r.name+" "+r.sex);
}
}
}
}
public class ThreadCommunication {
public static void main(String[] args) {
Resource r = new Resource();
InRunnable in = new InRunnable(r);
OutRunnable out = new OutRunnable(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
添加同步锁后,问题解决:
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
mike man
mike man
mike man
mike man
mike man
mike man
mike man
mike man