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

*************************************************************************************
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()就会生产一个,取出一个
而我的怎么还是一连取出好几个一样的;
------解决方案--------------------
if
else包含对象的位置不对。。。
*************************************************************************************
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)