java多线程――线程间的通讯
来源:程序员人生 发布时间:2015-04-28 08:17:14 阅读次数:3784次
public class ThreadDemo3 {
public static void main(String[] args) {
Resource res = new Resource();
Input input = new Input(res);
Output output = new Output(res);
Thread t1 = new Thread(input);
Thread t2 = new Thread(output);
t1.start();
t2.start();
}
}
class Resource {
String name;
String gender;
}
class Input implements Runnable {
Resource res;
Input(Resource res) {
this.res = res;
}
public void run(){
int x = 1;
while (true){
synchronized (Resource.class) {
if (x%2 == 0){
this.res.name = "Stephen Curry";
this.res.gender = "male";
} else {
this.res.name = "斯蒂芬 库里";
this.res.gender = "男人";
}
x++;
}
}
}
}
class Output implements Runnable {
Resource res;
Output(Resource res){
this.res = res;
}
public void run(){
while(true){
synchronized (Resource.class) {
System.out.println(this.res.name + "------" + this.res.gender);
}
}
}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠