I’m trying to run a Random method inside a Thread. I need to put this inside a thread because it kept hanging up my main UI Thread. But seems it’s not working. Log returns 0 size. I need help, code below.
public class RandomActivity extends Activity implements Runnable {
private TextView random;
Thread thread;
private boolean flagRandom;
private ArrayList<Integer> listRandom;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
thread = new Thread(this);
flagRandom = false;
listRandom = new ArrayList<Integer>();
random = (TextView) findViewById(R.id.txtRandom);
thread.start();
for(int i=0; i<5; i++) {
Log.i("RANDOM", listRandom.get(i).toString());
}
}
@Override
public void run() {
Random rNum = new Random();
while(flagRandom) {
for(int ctr=0; ctr<5; ctr++) {
if(ctr > 0) {
int iRand = rNum.nextInt(5) + 1;
if(listRandom.contains(iRand)) {
ctr--;
} else {
listRandom.add(iRand);
}
} else {
listRandom.add(rNum.nextInt(5) + 1);
}
}
}
}
}
As i review your code you
lograndom value afterthread.start();line . I want to tell you that thread always run in the background so when thread is in background and add random value into
listRandomyour below code is executed first . so it always return the 0.so you need to print it thread or print after thread stop . And one more thing your
flagRandomflag is also setfalsebefore start the execution of thread . so while loop not executed .