黑马程序员技术交流社区
标题:
帮我看下这段代码有什么问题,找了半天找不出来,错误提示已写在备注里
[打印本页]
作者:
王利强
时间:
2012-3-14 21:45
标题:
帮我看下这段代码有什么问题,找了半天找不出来,错误提示已写在备注里
class Res
{ String name;
String sex;
boolean flag=false;
}
class input implements Runnable
{ private Res r;
input(Res r)
{ this.r=r;
}
public void run()
{ int x=0;
while(true)
{ synchronized(r)
{if(flag)
try{r.wait();}catch(Exception e){}
if(x==0)
{
r.name="lili";
r.sex="girl";
}
else
{
r.name="张三";
r.sex="男";
}
x=(x+1)%2;
r.flag=true;
notify();
}
}
}
}
class output implements Runnable
{ private Res r;
output(Res r)
{
this.r=r;
}
public void run()
{while(true)
{synchronized(r)
{if (!flag)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"......"+r.sex);}
r.flag=false;
notify();
}
}
}
}//编译时提示这一行有错误,需要class,interface或enum
class waitDemo
{
public static void main(String[] args)
{ Res r=new Res();
input in=new input(r);
input out=new input(out);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
作者:
王利强
时间:
2012-3-14 21:46
主函数中input out=new input(r);改正后仍出现上述情况,崩溃了
作者:
王利强
时间:
2012-3-14 21:48
写错了,是output out=new output(r)改正后仍出现上述提示
作者:
程洪
时间:
2012-3-14 21:54
class Res {
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable {
private Res r;
Input(Res r) {
this.r = r;
}
public void run() {
int x = 0;
while (true) {
synchronized (r) {
if (false)
try {
r.wait();
} catch (Exception e) {
}
if (x == 0) {
r.name = "lili";
r.sex = "girl";
} else {
r.name = "张三";
r.sex = "男";
}
x = (x + 1) % 2;
r.flag = true;
notify();
}
}
}
}
class Output implements Runnable {
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
synchronized (r) {
if (!false)
try {
r.wait();
} catch (Exception e) {
}
System.out.println(r.name + "......" + r.sex);
}
r.flag = false;
notify();
}
}
}
// 编译时提示这一行有错误,需要class,interface或enum
class waitDemo {
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
复制代码
帮你修改后 编译通过 不过不太了解你的需求 能麻烦你把需求发出来吗?
作者:
王思兰
时间:
2012-3-14 22:19
一般这种错误都是多了或少了大括号
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2