0

我正在制作应用程序来听希腊语的 .mp3 单词并在 2000 毫秒后显示它们但是当我暂停线程然后 notify() 后线程永远不会再次运行... TextView 每 2000 毫秒更改一次但是当我暂停它并 notify() 运行时( ) 块不再执行任何操作并且应用程序崩溃.. 我做错了什么?

class MyinnerThread implements Runnable  {
    String name;
    Thread tr;
    boolean suspendFlag;
    int i = 0;

    MyinnerThread(String threadname) {
        name = threadname;
        tr = new Thread(this, name);
        suspendFlag = false;
        tr.start();
    }

    public void run() {

        try {
            while(!suspendFlag){

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if(i == 0){tv1.setText("trhead1");}
                    if(i == 1){tv2.setText("trhead2");}
                    if(i == 2){tv3.setText("trhead3");}
                    if(i == 3){tv4.setText("trhead4");}
                    if(i == 4){tv5.setText("trhead5");}
                    if(i == 5){tv6.setText("trhead6");}
                    if(i == 6){tv7.setText("trhead7");}
                    if(i == 7){tv8.setText("trhead8");}

                    synchronized(signal) {
                        while(suspendFlag) {
                            try {
                                signal.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });

            Thread.sleep(2000);
            i++;

           }
        } catch (InterruptedException e) {
            System.out.println(name + " interrupted.");
        }
    }
    void mysuspend() {
        suspendFlag = true;
    }

     void myresume() {

        synchronized(signal) {
            suspendFlag = false;
            signal.notify();
        }

}

}

编辑:这里的最终代码和工作!

run() {

    try {
        while(true){

         synchronized(signal) {
               while(suspendFlag) {
                     try {
                         signal.wait();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
              //....
                }
            }
        });

        Thread.sleep(2000);
        i++;
       }
    } 
}

}

4

1 回答 1

0
  1. signal.wait()从 UI 线程中调用(我假设,runOnUIThread将在 UI 线程上执行给定Runnable的)。这将阻止/冻结 UI。将其从方法中取出run()并放入线程“主循环”中。

  2. 重新考虑主循环while (!suspendFlag)!这将中止整个任务,而不仅仅是暂停它。

  3. 最后,suspendFlag volatile请避免可见性问题。

于 2013-11-11T16:36:03.973 回答