重新启动活动时,我的asynctasks之一未执行

时间:2018-12-21 20:02:09

标签: java android

我有9个异步任务在运行(8个来自1类,另外1个来自其他类),每当我重新启动活动时,前8个线程就会运行,但是有1个不同的线程没有,我找不到原因。< / p>

public class MainActivity extends AppCompatActivity {

TextView tv;

ImageView iv1;
ImageView iv2;
ImageView iv3;
ImageView iv4;
ImageView iv5;
ImageView iv6;
ImageView iv7;
ImageView iv8;

ImageView h1;
ImageView h2;
ImageView h3;

boolean salir;

int puntuacion;
int vidas;

Hilo hilo;
Hilo hilo2;
Hilo hilo3;
Hilo hilo4;
Hilo hilo5;
Hilo hilo6;
Hilo hilo7;
Hilo hilo8;

Ganar ganar;

int cerrar;
boolean fin;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    puntuacion = 0;
    vidas = 3;
    salir = false;
    cerrar = 0;
    fin = false;

    tv = findViewById(R.id.puntuacion);

    iv1 = findViewById(R.id.imageView);
    iv2 = findViewById(R.id.imageView2);
    iv3 = findViewById(R.id.imageView3);
    iv4 = findViewById(R.id.imageView4);
    iv5 = findViewById(R.id.imageView5);
    iv6 = findViewById(R.id.imageView6);
    iv7 = findViewById(R.id.imageView7);
    iv8 = findViewById(R.id.imageView8);

    h1 = findViewById(R.id.heart1);
    h2 = findViewById(R.id.heart2);
    h3 = findViewById(R.id.heart3);

    hilo = new Hilo(iv1);
    hilo2 = new Hilo(iv2);
    hilo3 = new Hilo(iv3);
    hilo4 = new Hilo(iv4);
    hilo5 = new Hilo(iv5);
    hilo6 = new Hilo(iv6);
    hilo7 = new Hilo(iv7);
    hilo8 = new Hilo(iv8);

    ganar = new Ganar();

    BlockingQueue<Runnable> mWorkQueue =
            new LinkedBlockingQueue<Runnable>(9);


    ThreadPoolExecutor mThreadPool =
            new ThreadPoolExecutor(
                    9,
                    9,
                    3,
                    TimeUnit.SECONDS,
                    mWorkQueue
            );

    hilo.executeOnExecutor(mThreadPool);
    hilo2.executeOnExecutor(mThreadPool);
    hilo3.executeOnExecutor(mThreadPool);
    hilo4.executeOnExecutor(mThreadPool);
    hilo5.executeOnExecutor(mThreadPool);
    hilo6.executeOnExecutor(mThreadPool);
    hilo7.executeOnExecutor(mThreadPool);
    hilo8.executeOnExecutor(mThreadPool);

    ganar.executeOnExecutor(mThreadPool);

    iv1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv1, hilo);
        }
    });
    iv2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv2, hilo2);
        }
    });
    iv3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv3, hilo3);
        }
    });
    iv4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv4, hilo4);
        }
    });
    iv5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv5, hilo5);
        }
    });
    iv6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv6, hilo6);
        }
    });
    iv7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv7, hilo7);
        }
    });
    iv8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click(iv8, hilo8);
        }
    });

}

public void updatePuntuacion() {
    tv.setText("Puntuacion: " + puntuacion);
}

public void updateVidas() {
    if(vidas==2) {
        h3.setVisibility(View.INVISIBLE);
    } else if(vidas==1) {
        h2.setVisibility(View.INVISIBLE);
    } else if(vidas==0) {
        h1.setVisibility(View.INVISIBLE);
    }
}

public void click(ImageView iv, Hilo h) {
    if(h.isEstado()) {
        puntuacion+=10;
        updatePuntuacion();
        h.setEstado(false);
        iv.setImageResource(R.drawable.blank);
    } else {
        vidas-=1;
        updateVidas();
    }
}

private class Hilo extends AsyncTask<Void, Void, Void> {
    public boolean isEstado() {
        return estado;
    }

    ImageView img;
    boolean ganado = false;
    boolean estado;

    public void setEstado(boolean estado) {
        this.estado = estado;
    }

    public Hilo (ImageView img) {
        this.img = img;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        estado = false;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        if(estado == true) {
            img.setImageResource(R.drawable.blank);
            estado = false;
        } else {
            img.setImageResource(R.drawable.topo);
            estado = true;
        }
    }

    @Override
    protected Void doInBackground(Void... voids) {

        while(!salir) {
            if(fin) {
                cancel(true);
            } else if(estado == true) {
                try {
                    Thread.sleep(Math.round(Math.random()*5000 + 3000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress();
            } else if(estado == false){
                try {
                    Thread.sleep(Math.round(Math.random()*500 + 3000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress();
            } else {
                publishProgress();
            }
        }
        return null;
    }

}

private class Ganar extends AsyncTask<Void, Void, Void> {

    public Ganar () {}

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        fin = true;
        Intent i = new Intent(MainActivity.this, ClasificacionesActivity.class);
        startActivity(i);
    }

    @Override
    protected Void doInBackground(Void... voids) {

        while(!salir) {
            if(vidas < 1) {
                salir = true;
            }
        }
        return null;
    }

}

public void onBackPressed(){

    if(cerrar > 0) {
        Intent a = new Intent(Intent.ACTION_MAIN);
        a.addCategory(Intent.CATEGORY_HOME);
        a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(a);
    } else {
        cerrar++;
        Toast.makeText(getApplicationContext(), "Vuelve a tocar atrás para cerrar la aplicación", Toast.LENGTH_SHORT).show();
    }

}

}

每次我重新启动活动时(当您松开游戏时,它都会进入另一个活动,您可以有意图地再次进入游戏),都会运行ilo asynctasks,但是Ganar asynctask不会,因此您无法再次松开。

>

1 个答案:

答案 0 :(得分:0)

您执行此操作的整个方法是错误的。如果需要使用Thread,则永远不要一直运行AsyncTask。而且让线程忙于循环以寻找要更改的变量从来都不是正确的方法,相反,您应该在更改变量时进行检查,甚至应使用信号量或rxjava之类的异步信号。

最后,除非声明变量为volatile,否则不能只声明一个变量并查看线程之间的变化。否则,编译器将对其进行优化,并且永远不会再实际从内存中获取值,而是使用本地缓存的版本。