我正在研究线程队列。我的目标是确保同一时间不超过一个烤面包重叠。示例在onCreate,onStart,onResume中烤面包。
首先,我为带有烤面包队列和活动上下文的烤面包助手创建一个类。该队列执行线程,直到队列中没有任何项目,但是此代码不起作用,我看不到任何吐司
班级
public class ToastCreater {
private static List<ToastSettings> _toastQueue = new ArrayList<>();
public static void CreateToast(final ToastSettings toastSettings) {
_toastQueue.add(toastSettings);
if (_toastQueue.size() != 0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
for (ToastSettings item : _toastQueue) {
Toast.makeText(item.getContext(), item.getMessage(), item.isLong() ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
if (item.isLong()) Thread.sleep(4000);//Long 3500ms Short 2000ms
else Thread.sleep(3000);
_toastQueue.remove(item);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
public static class ToastSettings {
private String Message;
private boolean IsLong;
private Context Context;
public android.content.Context getContext() {
return Context;
}
public ToastSettings setContext(android.content.Context context) {
Context = context;
return this;
}
public String getMessage() {
return Message;
}
public ToastSettings setMessage(String message) {
Message = message;
return this;
}
public boolean isLong() {
return IsLong;
}
public ToastSettings setLong(boolean aLong) {
IsLong = aLong;
return this;
}
}
}
用法:
ToastCreater.CreateToast(
new ToastCreater.ToastSettings()
.setContext(this.getBaseContext())
.setMessage("onCreate")
.setLong(true));