今天讲讲多线程通信,之前讲了多线程同步问题,也就是多线程操作同一个变量而导致出乎预料的结果,这结果不是我们想要的,比如上次讲的买票程序,票数会出现0号票问题,那个是单一的线程操作,线程之间通信,就是二个线程之间同一个对象中的数据,比如一个线程对对象中的数据进行赋值,一个线程取值,
代码:
public class ThreadTest1 {
public static void main(String[] args) {
Resouce r = new Resouce();
Input input = new Input(r);
Output output = new Output(r);
Thread t1 = new Thread(input);
Thread t2= new Thread(output);
t1.start();
t2.start();
}
}
class Resouce{
String name;
String sex;
}
/**
* 输入
* @author carpool
*/
class Input implements Runnable{
Resouce r;
public Input(Resouce r) {
super();
this.r = r;
}
@Override
public void run() {
int x=0;
while(true){
synchronized (r) {
if(x==0){
r.name="mike";
r.sex = "nan";
}else{
r.name="丽丽";
r.sex = "女";
}
//切换
}
x = (x+1)%2;
}
}
}
class Output implements Runnable{
Resouce r;
public Output(Resouce r) {
super();
this.r = r;
}
@Override
public void run() {
while(true){
synchronized (r) {
System.out.println(r.name+r.sex);
}
}
}
}
二个线程一个是输入线程 一个是输出线程
Input input = new Input(r);
Output output = new Output(r);
Thread t1 = new Thread(input);
Thread t2= new Thread(output);