gpt4 book ai didi

java - 如何同时运行两个 FOR 循环

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:47 27 4
gpt4 key购买 nike

我正在使用加速度计,第一个代码是震动检测器:(代码1)

if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
long now = System.currentTimeMillis();

//**********************************************************************
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}

if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(x + y + z - mLastX - mLastY - mLastZ) / diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = x;
mLastY = y;


mLastZ = z;

有了这个,当手机被摇动时,我会收到消息:(代码2)

  mSensorListener.setOnShakeListener(new OnShakeListener() {

@Override
public void onShake() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Shake!", Toast.LENGTH_SHORT).show();
}
});

我还有一个 for 循环,用于每 2 秒将加速度计值 x、y、z 保存到数组中:(代码3)

 if (lastUpdate == -1 || (curTime - lastUpdate) > 2000) {
lastUpdate = curTime;

x = values[0];
y = values[1];
z = values[2];

for (int column = 0; column < 3; column++) {
if (column == 0) {
p[row][column] = values[0];

}
if (column == 1) {
p[row][column] = values[1];
//yacc.setText("Os X: " + p[row][column]);
}
if (column == 2) {
p[row][column] = values[2];
//zacc.setText("Os X: " + p[row][column]);
}}
if (row == 0) {
xacc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 1) {
yacc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 2) {
zacc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 3) {
z2acc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
if (row == 4) {
z3acc.setText("Os X: " + p[row][0] + " " + p[row][1] +" " + p[row][2]);
}
row++;
if (row == 5) {
row = 0;
}

代码 3 永无止境,代码 1 是振动检测器。我怎样才能一起运行它,也许与线程(如何)或其他任何东西一起运行?

最佳答案

如果您想同时运行两个(或更多)循环,请使用 Threads。只需在一个线程中定义每个循环,然后启动您的线程 :)

示例:

第一个线程:

public class ThreadForLoopA extends Thread{
// variables for your Thread ...
@Override
public void run(){
// your first loop here ...
}
}

第二个线程:

public class ThreadForLoopB extends Thread{
// variables for your Thread ...
@Override
public void run(){
// your second loop here ...
}
}

像这样启动所有线程:

ThreadForLoopA threadA = new ThreadForLoopA();
ThreadForLoopB threadB = new ThreadForLoopB();

//start threads (the two loops will be executed at the same time)
threadA.start();
threadB.start();

关于java - 如何同时运行两个 FOR 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8360099/

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