Java多线程练习题(wait和notifyAll)

sxh53 2013-05-11 04:03:28
我弄一下午了 还是不太明白
题目要求一个线程计时(1秒1秒的计时),另一个线程根据计时线程,5秒钟输出一次。

这个NotifyAll是怎么回事啊,执行了它不一定立马跳到线程2是吗?
那跳到线程2是sleep开始之前还是之后呢?

等等问题
求一并解答。3Q

class th1 implements Runnable
{
private static int count;
th1()
{
count=0;
}
public static int getCount(){return count;}
public synchronized void waitme()
{
count++;
//if (count%5==0)
notifyAll();
System.out.print(count+" ");
}
public void run()
{
for(;;){

try{
Thread.sleep(1000);
waitme();

}catch(InterruptedException e){return;}


}}
}
class th2 implements Runnable
{

public synchronized void act()
{
try {
while(th1.getCount()%5!=0)
{
wait();
}
System.out.print("Finally"+th1.getCount()+" ");
// Thread.sleep(900);
}catch (InterruptedException e) {
return;
}


}
public void run()
{
for(;;){
act();

}
}
}
public class waitwait {
public static void main(String args[])
{
th1 t1=new th1();
th2 t2=new th2();
new Thread(t2).start();
new Thread(t1).start();
}
}
...全文
189 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhaogang 2013-05-11
  • 打赏
  • 举报
回复
LZ要注意Java命名规范。 notifyAll 是唤醒线程监视器上所有等待的线程,同理,notify 就是唤醒线程监视器上等待的某个线程(具体唤醒的哪个天知道)。 但唤醒归唤醒,只代表线程处于就绪状态,并一定轮到你所想的线程执行。 还有,LZ的程序写错了,只有在同一个synchronized中的线程监视器才是一致的,也就是你的th2类中写了wait(); 那th1类写再多的notifyAll也唤不醒th2线程。
//由于1秒和5秒的类一样,所以就写成一个类
class SecsThread extends Thread{
    private final String name;
    private PrintSecs ps;

    public SecsThread(String name; PrintSecs ps){
        this.name = name;
        this.ps = ps;
    }

    public void run{
        try{
          while(true)
              ps.printSece(name);
        }catch(InterruptedException e){}
    }
}

class PrintSecs{
    private final Object lock = new Object();
    private int count = 0;

    public void printSece(String stname) throws InterruptedException{
        synchronized(lock){
            //如果1secs取5的模等于0并且当前线程是1secs,那就唤醒其他线程,自己等待
            if((count%5 == 0) && (stname.equalsIgnoreCase("1secs"))){
                lock.notify();
                lock.wait();
            //同理,如果线程是5secs,那也是唤醒其他线程,自己等待
            }else if(stname.equalsIgnoreCase("5secs"))){
                lock.notify();
                lock.wait();                
            }
            System.out.println(stname + " - - " + count);
            count++;
        }
        Thread.sleep(1000);//睡1秒
    }
}

public static void main(String[] args){
    PrintSecs ps = new PrintSecs();
    SecsThread st1 = new SecsThread("1Secs",ps);
    SecsThread st5 = new SecsThread("5Secs",ps);

    st1.start();
    st5.start();
}
sxh53 2013-05-11
  • 打赏
  • 举报
回复
另外顺便说一下 th1是计时线程 th2是输出线程 真心感谢,捉摸一下午捉摸不透的心情大家理解吧!!!!!!!!

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧