2

I have my UI and other Thread, where there is loop:

while(true){

}

I am checking changes of String value in the system, and when changes, I send message via pre-opened socket to the server. Problem is, when applying loop, my app freezes, and CPU load is very high (about 90 %). I know, infinite loop must not be done in thread, but do you know how to copy this behavior, not using infinite loop?

Thx

Main Code (onCreate method):

    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;
}

Thread Code (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

   }
4

2 回答 2

7

如果您的循环确实在单独的线程中运行,那么问题在于它占用了 CPU。

与其轮询检查值的更改,不如编写一个触发来自另一个线程的服务器更新的设置器(例如,使用/协议)String(如果您可以控制相关代码)会更好。waitnotify

即使您必须轮询,您真的需要以 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。

于 2012-11-26T18:27:51.977 回答
1

正在做

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)
于 2012-11-27T02:19:23.330 回答