gpt4 book ai didi

android - 如何在Android中制作多线程代码?

转载 作者:行者123 更新时间:2023-11-29 18:04:37 27 4
gpt4 key购买 nike

我想做一个多线程程序,下面是我的试用。但只有 thread2 有效。如果我注释掉 thread2 部分,thread1 就可以工作了。如何让它们同时工作?谢谢!

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;

public class MainActivity extends Activity {
private EditText edittext1, edittext2;
volatile boolean bThreadRun = false;

MyThread1 myThread1;
MyThread2 myThread2;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

edittext1 = (EditText) findViewById(R.id.EditText1);
edittext2 = (EditText) findViewById(R.id.EditText2);

edittext1.setText("this is thread1");
edittext2.setText("this is thread2");
}

@Override
protected void onStart() {
super.onStart();
myThread1 = new MyThread1();
myThread1.start();
myThread2 = new MyThread2();
myThread2.start();
bThreadRun = true;
}

@Override
protected void onPause() {
super.onPause();
bThreadRun = false;
// myThread.stop();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

private Handler mHandler1 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
updateEditText1();
break;
}
};
};

private Handler mHandler2 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 2:
updateEditText2();
break;
}
};
};

public void updateEditText1() {
edittext1.append("thread1\n");
}

public void updateEditText2() {
edittext2.append("thread2\n");
}

public class MyThread1 extends Thread {
public MyThread1() {
}

@Override
public void start() {
super.start();
}

@Override
public void run() {
while (bThreadRun) {
try {
sleep(500);
Message message = new Message();
message.what = 1;
mHandler1.sendMessage(message);
} catch (InterruptedException ex) {
}
}
}
}

public class MyThread2 extends Thread {
public MyThread2() {
}

@Override
public void start() {
super.start();
}

@Override
public void run() {
while (bThreadRun) {
try {
sleep(500);
Message message = new Message();
message.what = 2;
mHandler2.sendMessage(message);
} catch (InterruptedException ex) {
}
}
}
}
}

最佳答案

这是因为处理程序实例是针对每个 Activity 的。所以你需要给两个线程传递同一个 Handler 实例,然后它应该可以工作。

关于android - 如何在Android中制作多线程代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14072104/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com