JAVA阻塞进程完成后执行

19 阅读1分钟

1.1.常见阻塞场景

** 阻塞队列有两个常见的阻塞场景, 它们分别是: (1) 当队列中没有数据的情况下, 消费者端的所有线程都会被自动阻塞(挂起) , 直到有数据放入队列。 (2) 当队列中填满数据的情况下, 生产者端的所有线程都会被自动阻塞(挂起) , 直到队列中有空的位置, 线程被自动唤醒。 支持以上两种阻塞场景的队列被称为阻塞队列。**

java

// 等待压缩任务完成,并获取结果
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = () -> FileUtils.compressMusicFilesToZip(context, fileList);
String filePath = executor.submit(task).get();

Kotlin 用协程

RxJava

Observable.fromCallable(() -> function())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(zipPath -> {

        }, throwable -> { 
            // 处理压缩异常的错误情况
            throwable.printStackTrace();
        });

androidx

CodeWrapper.speedLimit(mayFast, DeviceManager.getDeviceLanguage())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(deviceLanguage -> {
            loadProcessState.setValue(ProcessUiState.success());
            currentLanguage.setValue(deviceLanguage);
        }, error -> {
            loadProcessState.setValue(ProcessUiState.fail(error));
        });
package com.huawo.module_service.util;

import android.os.SystemClock;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.util.Supplier;

import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.Single;

public class CodeWrapper {

    private static final long SPEED_LIMIT_VALUE = 500;

    public static <T> T speedLimit(boolean unlimited, @NonNull Supplier<T> supplier) {
        if (unlimited) return supplier.get();
        long st = SystemClock.elapsedRealtime();
        T result = supplier.get();
        long duration = SystemClock.elapsedRealtime() - st;
        if (duration < SPEED_LIMIT_VALUE) {
            try {
//                Log.i("CodeWrapper", "speedLimit: " + (SPEED_LIMIT_VALUE - duration));
                Thread.sleep(SPEED_LIMIT_VALUE - duration);
            } catch (Exception e) {
                Log.w("CodeWrapper", "speedLimit - Supplier: sleep", e);
            }
        }
        return result;
    }

    public static <T> Single<T> speedLimit(boolean unlimited, @NonNull Single<T> single) {
        if (unlimited) return single;
        return Single.create(emitter -> {
            try {
                long st = SystemClock.elapsedRealtime();
                T result = single.blockingGet();
                long duration = SystemClock.elapsedRealtime() - st;
                if (duration < SPEED_LIMIT_VALUE) {
                    try {
//                        Log.i("CodeWrapper", "speedLimit: " + (SPEED_LIMIT_VALUE - duration));
                        Thread.sleep(SPEED_LIMIT_VALUE - duration);
                    } catch (Exception e) {
                        Log.w("CodeWrapper", "speedLimit - Single: sleep", e);
                    }
                }
                emitter.onSuccess(result);
            } catch (Exception e) {
                emitter.onError(e);
            }
        });
    }

    public static <T> Observable<T> speedLimit(boolean unlimited, @NonNull Observable<T> observable) {
        if (unlimited) return observable;
        return Observable.create(emitter -> {
            try {
                long st = SystemClock.elapsedRealtime();
                observable.subscribe(value -> {
                    emitter.onNext(value);
                }, error -> {
                    emitter.onError(error);
                }, () -> {
                    long duration = SystemClock.elapsedRealtime() - st;
                    if (duration < SPEED_LIMIT_VALUE) {
                        try {
//                            Log.i("CodeWrapper", "speedLimit: " + (SPEED_LIMIT_VALUE - duration));
                            Thread.sleep(SPEED_LIMIT_VALUE - duration);
                        } catch (Exception e) {
                            Log.w("CodeWrapper", "speedLimit - Single: sleep", e);
                        }
                    }
                    emitter.onComplete();
                });
            } catch (Exception e) {
                emitter.onError(e);
            }
        });
    }

    public static Completable speedLimit(boolean unlimited, @NonNull Completable completable) {
        if (unlimited) return completable;
        return Completable.create(emitter -> {
            try {
                long st = SystemClock.elapsedRealtime();
                completable.blockingAwait();
                long duration = SystemClock.elapsedRealtime() - st;
                if (duration < SPEED_LIMIT_VALUE) {
                    try {
//                        Log.i("CodeWrapper", "speedLimit: " + (SPEED_LIMIT_VALUE - duration));
                        Thread.sleep(SPEED_LIMIT_VALUE - duration);
                    } catch (Exception e) {
                        Log.w("CodeWrapper", "speedLimit - Completable: sleep", e);
                    }
                }
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        });
    }

}