/*线程间通讯: 其实就是多个线程在操作同一个资源, 但是操作的动作不同
* */
public class Communication {
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Res {// 通用资源
String name;
String sex;
}
class Input implements Runnable {// 存数据
private Res r;
Input(Res r) {
this.r = r;
}
@Override
public void run() {
int x = 0;
while (true) {
synchronized (r) {
if (x == 0) {
r.name = "zhangsan";
r.sex = "张三";
} else {
r.name = "lisi";
r.sex = "李四";
}
x = (x + 1) % 2;
}
}
}
}
class Output implements Runnable {// 取数据
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
synchronized (r) {
System.out.println(r.name + "..." + r.sex);
}
}
}
}