public class Sender {
private static String TAG = "sender";
private PriorityBlockingQueue<ImageInfo> blockingQueue = new PriorityBlockingQueue<ImageInfo>(100, new Comparator<ImageInfo>() {
@Override
public int compare(ImageInfo o1, ImageInfo o2) {
return o1.order - o2.order;
}
});
private static class SingleHolder {
private static Sender sender = new Sender();
}
public static Sender getInstance() {
return SingleHolder.sender;
}
private int last = 0;
private ExecutorService threadPool = Executors.newCachedThreadPool();
private static Random random = new Random();
public Sender() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
ImageInfo peekInfo = blockingQueue.peek();
if (peekInfo != null && last == peekInfo.order) {
try {
ImageInfo info = blockingQueue.take();
Log.i(TAG, "info.remoteUrl = " + info.remoteUrl);
} catch (InterruptedException e) {
e.printStackTrace();
}
last += 1;
} else {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
private int total = 0;
public synchronized void sendImages(List<String> uris) {
for (int i = 0; i < uris.size(); i++) {
final ImageInfo info = new ImageInfo(total + i, uris.get(i));
threadPool.execute(new Runnable() {
@Override
public void run() {
upload(info);
}
});
}
total += uris.size();
}
private void upload(ImageInfo imageInfo) {
try {
Thread.sleep(random.nextInt(5000));
imageInfo.remoteUrl = "remote: " + imageInfo.uri;
blockingQueue.add(imageInfo);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class ImageInfo {
int order;
String uri;
String remoteUrl;
public ImageInfo(int order, String uri) {
this.order = order;
this.uri = uri;
}
public void setRemoteUrl(String remoteUrl) {
this.remoteUrl = remoteUrl;
}
}
}
顺序发送图片
最新推荐文章于 2022-03-28 14:40:34 发布