package com.zzl.thread;
/**
* 线程间通讯
* 所谓线程间通讯,即多个线程操作同一资源,但是操作的动作不同。
* 下面演示的是线程间通讯出现的问题。
*/
class Resouce{
String name;
String sex;
}
class InRunnable implements Runnable{
private Resouce r;
public InRunnable(Resouce r){
this.r = r;
}
@Override
public void run() {
int x = 0;
while(true){
if(x == 0){
r.name = "mike";
r.sex = "man";
}else{
r.name = "胖胖胖胖胖胖胖胖";
r.sex = "女女女女女女";
}
x = (x+1)%2;
}
}
}
class OutRunnable implements Runnable{
private Resouce r;
public OutRunnable(Resouce r){
this.r = r;
}
@Override
public void run() {
while(true){
System.out.println(r.name+" "+r.sex);
}
}
}
public class ThreadCommunication {
public static void main(String[] args) {
Resouce r = new Resouce();
InRunnable in = new InRunnable(r);
OutRunnable out = new OutRunnable(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
[color=red]运行结果出问题了[/color]:
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 man
mike 女女女女女女
mike 女女女女女女
mike 女女女女女女
mike man
mike man
胖胖胖胖胖胖胖胖 女女女女女女
mike 女女女女女女
mike 女女女女女女
胖胖胖胖胖胖胖胖 man
胖胖胖胖胖胖胖胖 man
mike man
mike man
胖胖胖胖胖胖胖胖 女女女女女女
胖胖胖胖胖胖胖胖 女女女女女女
mike 女女女女女女
mike 女女女女女女
胖胖胖胖胖胖胖胖 man
mike 女女女女女女