优化之前都是对的。一优化,输出就是满页的丽丽。。女 或者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();
}
}
}
还有。。怎么直接把代码弄上来还带行号还可以复制的。。。
|