线程池
ExecutorService executors = Executors.newFixedThreadPool(4);
for (int i = 0; i < 5; i++) {
int finalI = i;
executors.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(finalI * 1000 + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "run: thread id" + Thread.currentThread().getId());
}
});
}
AsyncTask
class MyAsyncTask extends AsyncTask<String,Integer,String>{
ProgressBar progressBar;
TextView textView;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = findViewById(R.id.pb_show);
progressBar.setProgress(0);
textView = findViewById(R.id.tv_show);
textView.setText("processing");
}
@Override
protected String doInBackground(String... strings) {
int current = 0;
for (String string : strings) {
try {
Thread.sleep(200);
Log.d(TAG, "doInBackground: " + string);
current += 10;
publishProgress(current);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "successfully";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
Log.d(TAG, "onPostExecute: " + Thread.currentThread().getName());
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
}
String[] strings = new String[10];
for (int i = 0; i < 10; i++) {
strings[i] = "string_" + i;
}
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(strings);