package com.example.imageloaderpratise;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initBackThread();
for(int i = 0 ; i < 10 ; i++){
addTask(i);
}
}
private void initBackThread() {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
backHandler = new Handler(){
public void handleMessage(Message msg) {
int tag = (int) msg.obj;
threadPool.execute(getTask());
Log.e("xxx", "handlerTag:" + tag);
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
};
backSemaphore.release();
Looper.loop();
}
}).start();
}
private void addTask(int i){
mTask.add(getTask(i));
if(backHandler == null){
try {
backSemaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message message = backHandler.obtainMessage();
message.obj = i;
backHandler.sendMessage(message);
}
private synchronized Runnable getTask(){
return mTask.removeLast();
}
LinkedList<Runnable> mTask = new LinkedList<Runnable>();
Semaphore semaphore = new Semaphore(3);
Semaphore backSemaphore = new Semaphore(0);
ExecutorService threadPool = Executors.newFixedThreadPool(2);
Handler backHandler;
/*Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
};
};*/
protected Runnable getTask(final int tag) {
return new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("xxx", Thread.currentThread().getName() + ":" + "执行完将释放..." + "tag:" + tag);
semaphore.release();
Log.e("xxx", Thread.currentThread().getName() + ":" + "执行完将释放了***" + "tag:" + tag);
}
};
}
}
JAVA并发:使用Sempare, Handler和线程池写的加载框架
最新推荐文章于 2024-08-23 10:00:21 发布