首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Eclipse开发 >

新手问个不会的有关问题

2013-07-09 
新手问个不会的问题啊*******************************************************************************

新手问个不会的问题啊
新手问个不会的有关问题
*************************************************************************************


public class ThreadCommunicate {

/**
 * @a
 */
public static void main(String[] args) {
Q q = new Q();
new Thread(new producer(q)).start();
new Thread(new consumer(q)).start();
}

}

class producer implements Runnable {
Q q;

public producer(Q q) {
this.q = q;
}

public void run() {
int i = 0;
while (true) {
synchronized (q) {
if (q.noFull) 
try {
q.wait();
} catch (Exception e) {

}


else {


if (i == 0) {
q.name = "张三";
q.sex = "男";
} else {
q.name = "李四";
q.sex = "女";
}
q.noFull = true;
q.notify();
}
i = (i + 1) % 2;

}

}
}

}

class consumer implements Runnable {

Q q;

public consumer(Q q) {
this.q = q;
}

public void run() {
while (true) {
synchronized (q) {
if (!q.noFull) 
try {
q.wait();
} catch (Exception e) {

}
 else {

System.out.print(q.name + " ");
System.out.println("的性别是:" + q.sex);
System.out.println();
}
q.noFull = false;
q.notify();
}
}
}

}

class Q {
String name = "unknow";
String sex = "unknow";
boolean noFull = false;
}
********************************************************************
以上是代码,我看的java教学视频,那个老师讲用了wait()和notify()就会生产一个,取出一个
而我的怎么还是一连取出好几个一样的;新手问个不会的有关问题
java 线程
[解决办法]
if
else包含对象的位置不对。。。


package test;

public class ThreadCommunicate {

/**
 * @a
 */
public static void main(String[] args) {
Q q = new Q();
new Thread(new producer(q)).start();
new Thread(new consumer(q)).start();
}

}

class producer implements Runnable {
Q q;

public producer(Q q) {
this.q = q;
}

public void run() {
int i = 0;
while (true) {
synchronized (q) {
if (q.noFull)


try {
q.wait();
} catch (Exception e) {

}

else {

if (i == 0) {
q.name = "张三";
q.sex = "男";
} else {
q.name = "李四";
q.sex = "女";
}
q.noFull = true;
i = (i + 1) % 2;
q.notify();
}


}

}
}

}

class consumer implements Runnable {

Q q;

public consumer(Q q) {
this.q = q;
}

public void run() {
while (true) {
synchronized (q) {
if (!q.noFull)
try {
q.wait();
} catch (Exception e) {

}
else {

System.out.print(q.name + " ");
System.out.println("的性别是:" + q.sex);
q.noFull = false;
q.notify();
}
}
}
}

}


调好了。楼主看下

热点排行