如果您不想使用静态概念,则可以传递参数中的任何内容。在下面的代码中,我已经实现了两个类。正如你所问,我在两个线程类中都使用了通用处理程序。我将处理程序h1作为Runnable对象的参数和start()方法传递给另一个线程类的run()方法。包含run()方法的线程是UI(Main)线程。我们必须使用UI线程来更新UI。工作者(后台)线程无法做UI更新。工人与UI之间的通信是通过处理程序完成的。所以,我在UI线程类中定义了处理程序h2。当从后台线程类调用UI线程类构造函数时,我从构造函数获取来自h1的h2值。我用h2进行沟通。实际上,h2和h1属于系统中相同的内存空间。
我在两个类下面做了线程通信供您参考。
一流
public class MainActivity extends AppCompatActivity {
Handler h1;
Thread t;
EditText editText;
private Bundle bb = new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
h1 = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
bb = msg.getData();
String str = bb.getString("udd");
editText.setText(str);
System.out.println(str);
}
};
t = new Thread(new MyRunnable(h1)); //I pass Runnable object in thread so that the code inside the run() method
//of Runnable object gets executed when I start my thread here. But the code executes in new thread
t.start(); //thread started
try {
t.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
二等
public class MyRunnable implements Runnable {
private Handler h2;
public MyRunnable(Handler h) {
this.h2 = h;
}
@Override
public void run() {
//everything inside rum method executes in new thread
for(int i=0;i<10;i++) {
Message m = Message.obtain(); //get null message
Bundle b = new Bundle();
b.putString("udd", "daju");
m.setData(b);
//use the handler to send message
h2.sendMessage(m);
}
}
}
注意:当thread.start()发生时,它触发了Runnable类的运行,它会创建一个单独的线程。所以每次调用start()时,都会有一个与被调用者线程具有相同优先级的新线程。
希望,这对你有帮助。
谢谢!它为我工作。 – Gokul
我很高兴男士@ gd16 –