黑马程序员技术交流社区
标题:
同步问题请教
[打印本页]
作者:
doyxy
时间:
2014-3-14 21:30
标题:
同步问题请教
本帖最后由 doyxy 于 2014-3-14 21:43 编辑
犯了低级错误,if把后面的东西全括进去了,晕死
看毕老师day12的视频,发现怎么改都运行不了,仔细查看了代码,和视频里的一样,,但是运行起来就是没有输出,空白的,实在是找不到哪里出问题了,请大家指点一下
public class ThreadCommunication {
/*
* 设计一个简单的多线程同时操作一个对象的例子,解决安全问题 创建两个线程,一个输入姓名性别,一个输出姓名性别;
* 当输入没有完成时,有可能发生输出错误,需要解决; 输入与输出需要加锁 进一步的,想要输入数值后,等待输出完毕才继续输入,
* 需要两个线程判断资源内是否有值,没有则输入然后等待,有则输出然后等待 两个线程间需要一个联系方式来互相通知
*/
public static void main(String[] args) {
Res r = new Res();
InputDemo in = new InputDemo(r);
OutputDemo out = new OutputDemo(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Res {// 创建资源类
String name;
String sex;
boolean flag=false; // 默认为false,表示目前没有资源;
}
class InputDemo implements Runnable {
private Res r;
InputDemo(Res r) {// 需要操作的是资源对象
this.r = r;
}
public void run() {// 操作方法,打印
int x=0;
while (true) {
synchronized (r) {
if (r.flag) {
try {r.wait();} catch (InterruptedException e) {}
if (x==0) {
r.name = "name";
r.sex = "sex";
} else {
r.name = "姓名";
r.sex = "性别";
}
x=(x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
}
class OutputDemo implements Runnable {
private Res r;
OutputDemo(Res r) {// 需要操作的是资源对象
this.r = r;
}
public void run() {
while (true) {
synchronized (r) {
if (!r.flag) {
try {r.wait();} catch (InterruptedException e) {}
System.out.println(r.name + "---" + r.sex);
r.flag = false;
r.notify();
}
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2