主题:求助,关于在线程中使用wait(),notify()
bixentegh
[专家分:0] 发布于 2008-02-04 16:28:00
小弟是初学java的菜鸟,有个关于线程的问题想请教大家
问题是这样的,有两个线程类,
第一个线程是一个循环以一定的速率打印出一串数字,
第二个线程是一个循环以一定的速率打印出一串字母,
同时开始两个线程,如何用wait(),notify() 和 join(),使得所有的数字都在字母之前打印出来
麻烦高手们帮帮忙!谢谢了
附件中是我写的代码,大家要是有时间的话麻烦帮小弟看看,感激不尽!
回复列表 (共1个回复)
沙发
happyboy2007 [专家分:3900] 发布于 2008-02-05 19:49:00
class Demo
{
public Demo()
{
Numbers n = new Numbers(this);
Letters l = new Letters(this);
n.start();
l.start();
}
public synchronized void printNumber()
{
for (int i=0;i<10;i++)
{
System.out.print(i);
try
{
Thread.currentThread().sleep(50);
}
catch(Exception ex)
{
}
}
try
{
this.notify();
this.wait(5000);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public synchronized void printLetter()
{
for (int i=0;i<10;i++)
{
System.out.print((char)(i+65));
try
{
Thread.currentThread().sleep(50);
}
catch(Exception ex)
{
}
}
try
{
this.notify();
this.wait(5000);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String [] args)
{
new Demo();
}
}
class Numbers extends Thread
{
private Demo demo;
public Numbers(Demo demo)
{
this.demo = demo;
}
public void run()
{
demo.printNumber();
}
}
class Letters extends Thread
{
private Demo demo;
public Letters(Demo demo)
{
this.demo = demo;
}
public void run()
{
demo.printLetter();
}
}
我来回复