no_russion 2019-09-11 23:34 采纳率: 33.3%
浏览 395
已采纳

多线程练习小问题 为什么这题notify不起作用

想要用多线程打印出12A34B56C78D.......
但是像这样写只能打出12,notify没有起作用,请问如何改动

public class 作业2
{

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        new Thread(new Number()).start();
        new Thread(new Letter()).start();
    }

}

class Number implements Runnable
{
    private int n = 1;

    @Override
    public synchronized void run()
    {
        for (int i = 0; i < 52; i++)
        {
            if (i % 2 == 0 && i != 0)
            {
                try
                {
                    notify();;
                    this.wait();
                } catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.print(n + i);
        }
    }
}

class Letter implements Runnable
{
    char a = 'a';

    @Override
    public synchronized void run()
    {
        try
        {
            wait();
        } catch (InterruptedException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        for (int i = 0; i < 26; i++)
        {
            System.out.print(a + i);
            try
            {
                notify();
                this.wait();
            } catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
  • 写回答

1条回答 默认 最新

  • 毕小宝 博客专家认证 2019-09-12 09:07
    关注

    这里需要理解 Object 类的 wait() 和 notify() 、notifyAll() 的用法,它是针对内置条件队列的阻塞和唤醒,一旦调用 wait 后,当前线程已经挂起了,即使后面的代码用了 notify,也是无效的,必须由另一个线程调用 notify 才能唤醒它。所以这里的用法是错误的,你这里是定义了两个线程,各自操作自己的 wait 和 notify ,在调用 wait 后就挂起了自己,由于没有其他线程调用 notify ,所以线程都处于挂起状态的。

    正确的应该是在一个类的不同方法中,一个方法用 wait() 挂起,另一个方法中用 notify 唤醒。并且这两个方法应该由不同的线程来调用。
    参考下这篇 https://blog.csdn.net/wojiushiwo945you/article/details/42262149 的 InnerConditionQueue 的用法,再试试。

    demo 中启动了三个线程 + main 线程:

    Thu Sep 12 09:18:17 CST 2019 buffer is Not Full notify:tt1
    Thu Sep 12 09:18:17 CST 2019 buffer is Not Full notify:tt3
    Thu Sep 12 09:18:17 CST 2019 buffer is Full thread wait:tt2
    Thu Sep 12 09:18:22 CST 2019 main take:hello1
    Thu Sep 12 09:18:22 CST 2019 buffer is Not Full notify:tt2
    

    t1 put、t3 put 后队列满了,此时 t2 再 put 时遇上了 wait 而阻塞。
    maint 线程消费了一个后,唤醒了 t2 线程。即 wait 和 notify 必须由不同的线程调用,否则将无法唤醒。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算