早上好,我的代码有问题,我有一个线程会根据按下的按钮生成一个数字,而在另一个线程中,我想检索此值并通过方法发送它,但是我无法恢复此值,它总是重置为零,我可以在线程之间共享该值
第一个线程生成数据值:
Thread coletaDados = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
dados = avancaEE + sobe + desce + avancaED + recuaED + recuaEE;
// Log.i("Thread Dados", "Valor dos Dados" + dados);
Thread.sleep(100);
}
}catch (InterruptedException e) {
}
}
});
coletaDados.start();
public class ThreadEnvio extends Thread {
byte[] EnvioManual = new byte[10];
ChecksumSend checksumSend = new ChecksumSend();
private int Dados;
SerialPortManager spManager;
InseticidaManualFragment inseticidaManualFragment = new InseticidaManualFragment();
第二个线程使用数据值:
public ThreadEnvio()
{
// this.Dados = dados;
spManager = SerialPortManager.getInstances();
}
@Override
public void run() {
try {
while (true) {
Dados = inseticidaManualFragment.dados;
//Dados = inseticidaManualFragment.dados;
Log.d("Pressed", "dados" + Dados);
EnvioManual[0] = (0x04);
EnvioManual[1] = (0x10);
EnvioManual[2] = (0x00);
EnvioManual[3] = (0x00);
EnvioManual[4] = (byte) 0xff;
EnvioManual[5] = (0x00);
EnvioManual[6] = (0x02);
EnvioManual[7] = (byte) (Dados >> 8);
EnvioManual[8] = (byte) (Dados & 0xff);
EnvioManual[9] = checksumSend.Calculachecksum(EnvioManual);
send(EnvioManual);
// Log.d("Saida", "Enviando" + toHexString(EnvioManual));
Thread.sleep(100);
}
}
catch (InterruptedException e) {
}
}
public void send (byte[] x ){
spManager.send(SerialPortManager.ttyS0,true,":" + toHexString(x) + "\r\n");
}
public static String toHexString(byte[] bytes){
char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length*2];
int v;
for(int j=0;j<bytes.length;j++){
v = bytes[j] & 0xFF;
hexChars[j*2] = hexArray[v/16];
hexChars[j*2 + 1] = hexArray[v%16];
}
return new String(hexChars);
}
}
答案 0 :(得分:0)
我认为最好的方法是使用一个共享对象在多个线程之间共享数据,其中一个线程将设置值,而其他线程将检索该值。
通过这种方式,您可以在共享库上进行同步,以避免经典的读写器问题。