黑马程序员技术交流社区
标题:
多线程的等待唤醒机制小问题
[打印本页]
作者:
孟子飞宏
时间:
2015-1-13 08:09
标题:
多线程的等待唤醒机制小问题
本帖最后由 孟子飞宏 于 2015-1-13 08:11 编辑
我写下面错误的代码的结果看图1<div class="blockcode"><blockquote>/*
线程间通讯:
多个线程在处理同一资源,但是任务却不同。
*/
class Resource
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable
{
Resource r;
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
{
try
{
r.wait();
}
catch (InterruptedException e)
{
}
}
else
{
if(x==0)
{
r.name = "mike";
r.sex = "nan";
}
else
{
r.name = "丽丽";
r.sex = "女";
}
r.notify();
r.flag = true;
}
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
Resource r;
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try
{
r.wait();
}
catch (InterruptedException e)
{
}
}
{
System.out.println(r.name+"..."+r.sex);
r.notify();
r.flag = false;
}
}
}
}
}
class ResourceDemo2
{
public static void main(String[] args)
{
//创建资源
Resource r = new Resource();
//创建任务
Input in = new Input(r);
Output out = new Output(r);
//创建线程
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}
复制代码
正确代码:
/*
线程间通讯:
多个线程在处理同一资源,但是任务却不同。
*/
class Resource
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable
{
Resource r;
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
{
try
{
r.wait();
}
catch (InterruptedException e)
{
}
}
// else
// {
if(x==0)
{
r.name = "mike";
r.sex = "nan";
}
else
{
r.name = "丽丽";
r.sex = "女";
}
r.notify();
r.flag = true;
// }
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
Resource r;
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try
{
r.wait();
}
catch (InterruptedException e)
{
}
}
{
System.out.println(r.name+"..."+r.sex);
r.notify();
r.flag = false;
}
}
}
}
}
class ResourceDemo2
{
public static void main(String[] args)
{
//创建资源
Resource r = new Resource();
//创建任务
Input in = new Input(r);
Output out = new Output(r);
//创建线程
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}
复制代码
:
错误.PNG
(48.16 KB, 下载次数: 0)
下载附件
2015-1-13 08:06 上传
图1
正确.PNG
(23.23 KB, 下载次数: 0)
下载附件
2015-1-13 08:09 上传
作者:
孟子飞宏
时间:
2015-1-13 08:12
也就37,38,53行把else注释就正确了,不知道为什么
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2