信号量Semaphore平时一般开发中不算是常见的api,但是他能给你提供管理多线程调度的能力。接下来我们用一个简单例子来演示他的作用。
假设情景,一个页面有个多个异步请求,我需要管理他们,要他们按照顺序一个接一个执行,这里我们就可以使用信号量完成。
具体含义看注释:
封装的工具类:
public class PNSyncTaskUtils implements Runnable {
public static final int action_pre_sync=1778;
public static final int action_later_sync=1779;
private static final ExecutorService EXECUTOR=Executors.newSingleThreadExecutor();// 单个的线程池
private Semaphore semaphore;
private Handler.Callback callback;
private Handler handler;
public PNSyncTaskUtils(Handler.Callback callback) {
this.callback = callback;
handler=new Handler(callback);
semaphore = new Semaphore(0);
EXECUTOR.submit(this);
}
//释放信号量
public synchronized void release() {
this.semaphore.release();
}
@Override
public void run() {
handler.sendMessage(PNBaseActivity.getMsgObj(action_pre_sync, this));
try {
semaphore.acquire();
} catch (Exception e) {
e.printStackTrace();
}
handler.sendMessage(PNBaseActivity.getMsgObj(action_later_sync, this));
}
}
调用场景:
public class TestActivity extends AppCompatActivity {
private PNSyncTaskUtils syncTaskUtils;
private PNSyncTaskUtils syncTaskUtils2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cx_test_activity);
syncTaskUtils = new PNSyncTaskUtils(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what==PNSyncTaskUtils.action_pre_sync)
{
//模仿网络请求
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//网络请求的回调
syncTaskUtils.release();
}
}).start();
}
if (msg.what==PNSyncTaskUtils.action_later_sync)
{
Toast.makeText(getApplicationContext(), "这个任务执行完毕", Toast.LENGTH_LONG).show();
}
return false;
}
});
syncTaskUtils2 = new PNSyncTaskUtils(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what==PNSyncTaskUtils.action_pre_sync)
{
//模仿网络请求
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//网络请求的回调
syncTaskUtils2.release();
}
}).start();
}
if (msg.what==PNSyncTaskUtils.action_later_sync)
{
Toast.makeText(getApplicationContext(), "这个任务执行完毕2", Toast.LENGTH_LONG).show();
}
return false;
}
});
}
}