簡體   English   中英

線程中的Android無限循環

[英]Android infinite loop in thread

我有我的UI和其他Thread,其中有循環:

while(true){

}

我正在檢查系統中String值的變化,當更改時,我通過預先打開的套接字向服務器發送消息。 問題是,當應用循環時,我的應用程序凍結,CPU負載非常高(約90%)。 我知道,無限循環不能在線程中完成,但是你知道如何復制這種行為,而不是使用無限循環嗎?

謝謝

主要代碼(onCreate方法):

    mProgressDialog = ProgressDialog.show(main.this, "loading","loading", true);
    c=new Client(this.getApplicationContext(), "192.168.0.121", 3333);
    c.start();

    CLIENT_MESSAGE="login user2 user2";
    synchronized(c){
        c.notify();
    }
    Client.zHandler.setEmptyMessage(119);


    mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg)
        {
            super.handleMessage(msg);

            switch (msg.what)
            {
                case 11:
                    Log.d("Logged in", "login");
                    mProgressDialog.dismiss();
                    break;
                case 12:    
                    Log.d("Logged out", "logout and end");
                    mProgressDialog.dismiss();
                    finish();
                    break;

                        }
                 }
          };

  @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {

    case KeyEvent.KEYCODE_BACK:
        CLIENT_MESSAGE="logout";
        synchronized (c) {
            c.notify();
        }
                    Client.zHandler.setEmptyMessage(129)
        break;
    default:

    }
    return true;
}

線程代碼(Client.java):

public Client(Context ctx, String hostname, int port){
    this.ctx=ctx;
    this.hostname=hostname;
    this.port=port;

    zHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg)
        {
            super.handleMessage(msg);

            switch (msg.what)
            {
                case 119://login
                    Log.d("119", "case 119");
                    messageText=DropboxFileClientActivity.CLIENT_MESSAGE;
                    main.mHandler.sendEmptyMessage(11);
                    break;
                case 129://logout
                    messageText=DropboxFileClientActivity.CLIENT_MESSAGE;
                    main.mHandler.sendEmptyMessage(12);
                    break;
                case 100:   
                    break;

                        }
                 }
          };
}
    public void run(){
      try {
        clientSocket = new Socket(hostname, port);
        //inputLine = new BufferedReader(new InputStreamReader(System.in));

        os = new ObjectOutputStream (clientSocket.getOutputStream());

        is = new ObjectInputStream(clientSocket.getInputStream());
    }
    catch (UnknownHostException e) {
        Log.d("ERROR", "unknown host "+hostname); 
    }
    catch (IOException e) {
        Log.d("ERROR2", "no bind"+hostname);
        e.printStackTrace();
    }

    while (!isInterrupted()) {
        try{
            synchronized (this) {
                wait();
            }
        } catch (InterruptedException e) {
            break; // interrupting the thread ends it
        }
        if (clientSocket != null && os != null && is != null &&!messageText.equals("")) {
                messageText="";
                //sending message to server, getting reply and displaying it to the screen
            } 
      }//endwhile loop

   }

如果你的循環確實在一個單獨的線程中運行,那么問題是它是一個CPU占用的。

不是輪詢以檢查String值的更改,而是編寫一個從另一個線程觸發服務器更新的setter(例如, wait / notify協議)會更好(如果您可以控制相關代碼) )。

即使你必須輪詢,你真的需要以CPU速度進行嗎? 或許一秒一次會做什么? 那會讓你在剩下的時間里睡覺。

至少,每次循環調用Thread.yield()

編輯根據您對帖子的評論,您應該在后台線程中等待:

在你的后台線程中:

while (!isInterrupted()) {
    synchronized (this) {
        wait();
    } catch (InterruptedException e) {
        break; // interrupting the thread ends it
    }
    // read string and send it to the server
}

在事件處理程序中:

public void onSomethingHappened(...) {
    // update the string
    synchronized (mThread) {
        mThread.notify();
    }
}

除非在同一對象上同步讀取和更新,否則應將字符串標記為volatile。

synchronized(blah){
    blah.wait();
}

是舊的同步方式。 查看java.util.concurrent包中的一些類。

例如,在您的活動中,您可以實現/添加TextWatcher,並在方法中使用

blockingQueue.put(theChangedText) //preferably you would do the put via an access method.

然后在你的主題中你會粗略地:

obj = blockingQueue.take()
sendToServer(obj)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM