黑马程序员技术交流社区
标题:
关于优化唤醒机制问题
[打印本页]
作者:
Teale
时间:
2014-3-14 14:40
标题:
关于优化唤醒机制问题
优化之前都是对的。一优化,输出就是满页的丽丽。。女 或者mike。。。man 唤醒出问题了。看了半天也不知道问题出在哪
package 多线程;
public class 唤醒机制 {
public static void main(String[] args){
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex){
if(flag==true){
try{this.wait();}catch(Exception e){}
}
else{
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
}
public synchronized void get(){
if(flag==false){
try{this.wait();}catch(Exception e){}
}
else{
System.out.println(this.name+"........"+this.sex);
this.flag=false;
this.notify();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r=r;
}
public void run (){
int x=0;
while(true){
if(x==0){
r.set("make", "man");
}
else{
r.set("丽丽", "女");
}
x=(x+1)%2;
}
}
}
class Output implements Runnable{
private Res r;
public Output(Res r){
this.r=r;
}
public void run(){
while(true){
r.get();
}
}
}
还有。。怎么直接把代码弄上来还带行号还可以复制的。。。
作者:
Teale
时间:
2014-3-14 15:06
zengming13 发表于 2014-3-14 14:45
你这是毕老师教程里的程序,你教程都没看,就来这里问!
你这是故意来骗技术分的
发贴教程在这:http://bbs ...
不看教程能知道这代码么? 动动脑子再回复好么? 我已经找到原因了,class Res类中 set方法 if后面不能接else ,上面wait()线程被唤醒时 运行直接跳出,所以导致问题所在。 毕老师视频简写if else,没带括号,我习惯带括号的。所以看错了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2