代码之家  ›  专栏  ›  技术社区  ›  Sudarshan Taparia

Android多线程

  •  0
  • Sudarshan Taparia  · 技术社区  · 5 年前

    我正在尝试用Android开发简单的多线程应用程序。下面是我的代码:

    package com.sudarshan.mythread;
    import android.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.EditText;
    
    public class MainActivity extends AppCompatActivity implements Runnable {
    
    EditText t;
    StringBuffer buffer = new StringBuffer();
    @Override
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t=(EditText) findViewById(R.id.editText);
        int n = 8; // Number of threads
        for (int i=0; i<n; i++)
        {
            Thread object = new Thread(new MainActivity());
            object.start();
            t.setText(buffer.toString());
        }
    }
    public void run()
    {
        try
        {
            // Displaying the thread that is running
    
    
            buffer.append ("Thread " +
                    Thread.currentThread().getId() +
                    " is running");
    
        }
        catch (Exception e)
        {
            // Throwing an exception
            showMessage("Error","Error Message");
        }
    }
    public void showMessage(String title,String Message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    } }
    

    我试图在stringbuffer中显示数据。每次运行线程时,都应将数据追加到Stringbuffer中。但编辑文本不会显示任何内容。我做错了什么?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Nabin Bhandari    5 年前

    你写了 t.setText(buffer.toString()); 线程启动后立即启动。但到那时,缓冲区可能还没有更新。所以,更新 EditText 在缓冲区更新之后。

    buffer.append ("Thread " +
                Thread.currentThread().getId() +
                " is running");
    // Note: If you want to update UI from background thread, you should do it the following way.
    runOnUiThread(new Runnable() {
        public void run(){
            t.setText(buffer.toString());
        }
    });
    

    此外,正如@Bek所说,您应该替换 new MainActivity() 具有 this .