黑马程序员技术交流社区
标题:
线程代码问题<已解决>
[打印本页]
作者:
袁錦泰
时间:
2012-5-29 00:48
标题:
线程代码问题<已解决>
本帖最后由 袁錦泰 于 2012-5-29 10:42 编辑
class Res {
private String name;
private String gender;
private boolean flag;
public synchronized void set(String name, String gender) {
if (this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
this.name = name;
this.gender = gender;
}
this.flag = true;
this.notify();
}
public synchronized void out() {
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(this.name + "," + this.gender);
}
this.flag = false;
this.notify();
}
}
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("zhangsan", "male");
} else {
r.set("lisi", "female");
}
x = (x + 1) % 2;
}
}
}
class Output implements Runnable {
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class InputOutputDemo {
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
复制代码
部分结果为:
zhangsan,male
zhangsan,male
zhangsan,male
zhangsan,male
zhangsan,male
lisi,female
lisi,female
lisi,female
lisi,female
lisi,female
zhangsan,male
zhangsan,male
复制代码
复习之前所学,我看了许久找不到问题所在,为何出书结果是批量输出,而不是有顺序的分别逐个输出.
请各位细心人帮忙分析一下哪里有错误.
作者:
罗文杰
时间:
2012-5-29 01:48
本帖最后由 罗文杰 于 2012-5-29 09:09 编辑
{:soso_e136:}原来写的理解错了,看了楼下了解到原来是else方法体的问题- -~~~
作者:
袁培育
时间:
2012-5-29 01:50
你的set函数里不能写else语句,把else删除(里面的代码还是要的,只是不加else)。如果有else的话执行一次if线程等待,被唤醒后直接执行else后的语句而不会执行else里的语句,因为if和else只能执行一个。
作者:
黄奕豪
时间:
2012-5-29 02:04
本帖最后由 黄奕豪 于 2012-5-29 02:08 编辑
楼主的代码格式真的挺看不惯的,所以调整了一下!
class Res
{
private String name;
private String gender;
private boolean flag = false;
public synchronized void set(String name, String gender)
{
if (flag)
{
try {
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
//else去掉,下面的一样,这里加上else的话他跟上面的if是一体的,如果线程执行了if,就不会执行else,当线程返回时,判断flag = true,进入等待,唤醒的时候因为已经判断过if了,所以不执行else里面的代码,直接跳过了赋值~~~
this.name = name;
this.gender = gender;
flag = true;
notify();
}
public synchronized void out()
{
if (!flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(this.name + "," + this.gender);
flag = false;//
notify();
}
}
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("zhangsan", "male");
}
else
{
r.set("lisi", "female");
}
x = (x + 1) % 2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while (true)
{
r.out();
}
}
}
public class InputOutputDemo {
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2