黑马程序员技术交流社区
标题:
请教问题:关于多线程同步。[已解决]
[打印本页]
作者:
李征雪
时间:
2012-4-6 14:43
标题:
请教问题:关于多线程同步。[已解决]
本帖最后由 李征雪 于 2012-4-6 15:58 编辑
//Demo1205.java
class Commodity//商品类
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void Input(String name)
{
this.name = name +"... ..."+count++;
while(true)
{
while (flag)
{
try
{
wait();
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"生产-->"+name);
flag = !flag;
notifyAll();
}
}
}
public synchronized void Output()
{
while(true)
{
while (!flag)
{
try
{
wait();
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"消费------>"+name);
flag = !flag;
notifyAll();
}
}
}
}
class PersonInput implements Runnable//生产类
{
Commodity com;
PersonInput(Commodity com)
{
this.com = com;
}
public void run()
{
com.Input("商品");
}
}
class PersonOutput implements Runnable//消费类
{
Commodity com;
PersonOutput(Commodity com)
{
this.com = com;
}
public void run()
{
com.Output();
}
}
class Demo1205
{
public static void main(String[] args)
{
Commodity com = new Commodity();
PersonInput pi = new PersonInput(com);
PersonOutput po = new PersonOutput(com);
Thread t1 = new Thread(pi);
Thread t2 = new Thread(po);
t1.start();
t2.start();
// System.out.println("Hello World!");
}
}
复制代码
学习毕老师第12天课程写的这段代码,弄了两个小时了,老是一大堆错,现在不报错了,但是没有运行结果,朋友们帮我看看哪里出问题了。
作者:
黄长利
时间:
2012-4-6 15:35
本帖最后由 黄长利 于 2012-4-6 15:36 编辑
//Demo1205.java
class Commodity//商品类
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void Input(String name)
{
this.name = name +"... ..."+count++;
while(true)
{
while (flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}
System.out.println(Thread.currentThread().getName()+"生产-->"+name);//
此句代码及以下应该写在while(flag)外面,否则,flag初始化为false,只能一直在外循环转悠了
flag = !flag;
notifyAll();
}
}
public synchronized void Output()
{
while(true)
{
while (!flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}
System.out.println(Thread.currentThread().getName()+"消费------>"+name);//此处同上面一样
flag = !flag;
notifyAll();
}
}
}
class PersonInput implements Runnable//生产类
{
Commodity com;
PersonInput(Commodity com)
{
this.com = com;
}
public void run()
{
com.Input("商品");
}
}
class PersonOutput implements Runnable//消费类
{
Commodity com;
PersonOutput(Commodity com)
{
this.com = com;
}
public void run()
{
com.Output();
}
}
class Demo1205
{
public static void main(String[] args)
{
Commodity com = new Commodity();
PersonInput pi = new PersonInput(com);
PersonOutput po = new PersonOutput(com);
Thread t1 = new Thread(pi);
Thread t2 = new Thread(po);
t1.start();
t2.start();
// System.out.println("Hello World!");
}
}
作者:
李征雪
时间:
2012-4-6 15:59
谢谢啊,太爽了,鼻子都通气了。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2