这段java代码有什么错误。这样写有什么不好。题目的意图是为了测试wait() notify()

来源:百度知道 编辑:UC知道 时间:2024/05/22 03:56:12
public class Thread_waiting {
public static void main(String[] args){
Methods m=new Methods();
new ThreadAB().start();
new ThreadC().start();
}

}
class Methods{
int flag=1;
boolean available=false;
public synchronized void fun1(){
if(available)
try{wait();} catch(Exception e){}
if(flag==1){
System.out.println("...Start.");
flag=2;
}
if(flag==3){
System.out.println("...End.");
flag=4;
}
available=true;
notify();
}
public synchronized void fun2(){
if(!available)
try{wait();} catch(Exception e){}
if(flag==2) {available=false;flag=3;notifyAll();}
if(flag==4) System.out.println("线程C自己结束");
}
}
class ThreadAB extends Thread{
Methods m=null;

public void run(){
m.fun1();
}
}
class ThreadC extends Thread{
M

wait() notify()是为了实现进程的同步。同步要求操作同一个对象,虽然你在Methods m=new Methods();

  new ThreadAB().start();

  new ThreadC().start();       新建了一个新对象m;

但随后的两个进程同样也新建了Methods对象,他们分别操纵自己的对象,根本实现不了同步!! 

我把这段程序进行了修改,把我写的程序放我空间里了,如有疑问请给我留言!

http://hi.baidu.com/a295508153/blog/item/00f1a0e96ad12436b90e2ddf.html

运行效果如下:

这Java段代码有什么错误啊 这段代码有什么错误 这段代码有什么错误阿 这段JS代码有什么错误? 请大家帮看看这段代码有什么错误 高手.帮看看这段ASP代码有什么错误!! 请问VB高手们,这段代码有什么错误? PHP 看我的这段代码有什么错误 请问这段代码有错误吗? 这段java代码是什么意思