所以我在我的应用程序上有2个线程(其中包括),一个修改对象(在示例中,设置一个矩形的位置)并调用方法,以便第二个线程可以在网络上发送它。
第一个帖子:
public void run(){
while(mIsRunning){
Log.i("MovingRectThread", "Run");
mX += 10;
mRect.setPos(mX,mY);
//Send Rect
mInterface.writeData(mRect);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
第二个帖子:
public void run(){
int commandSize=-1;
byte[] bufferR = new byte[ANSWER_SIZE];
int answerResult = 0;
while(mIsRunning){
Log.i("ProcessThreadGraphic", "Run");
switch(mState){
case IDLEREAD:
//****************
try {
commandSize = mmInStream.read(bufferR, 0, ANSWER_SIZE);
}
catch (IOException e) {
connectionLost();
}
// We received something
if(commandSize != -1 && bufferR[0] == 0x02){
answerResult = bufferR[2];
if(answerResult == 0){
//Authorize sending again
mState = IDLEWRITE;
}
}
//*********************
break;
case IDLEWRITE:
//Trying to send something
if(mBuffer != null ){
try {
mmOutStream.write(mBuffer);
mBuffer = null;
mState = IDLEREAD;
Thread.yield();
} catch (IOException e) {
connectionLost();
}
}
//**************
break;
default:
Log.e(TAG, "Error: state unknown");
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
和mInterface.writeData仅结束调用:
public void write(byte[]buffer){
mBuffer = buffer;
}
我的问题是,线程不能很好地协同工作:一个是在另一个重启之前循环多次,这不符合我的需要,你可以想象,我需要第一个修改我的对象一次,然后发送它的第二个线程,然后再次只修改对象...
希望我已经足够清楚了。