【发布时间】:2018-09-28 12:56:28
【问题描述】:
我正在编写一个按你输入的搜索机制 (android),它在后台线程中进行 sqlite 查询并将结果发布回 UI 线程。理想情况下,线程应该等待/睡眠,唤醒以执行任何接收到的 Runnable 对象并重新进入睡眠状态。实现这一目标的最佳方法是什么?为什么?
基本上我想了解这 3 个选项之间的主要区别是什么,以及哪一个最适合这个确切的场景
-
睡眠/中断
public class AsyncExecutorSleepInterrupt { private static Thread thread; private static Runnable runnable; static { thread = new Thread(() -> { while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { if (runnable != null) { runnable.run(); runnable = null; } } } }); thread.start(); } public static void execute(Runnable runnable) { AsyncExecutorSleepInterrupt.runnable = runnable; thread.interrupt(); }} -
等待/通知
public class AsyncExecutorWaitNotify { private static Thread thread; private static Runnable runnable; private static final Object monitor = new Object(); static { thread = new Thread(() -> { while (true) { synchronized (monitor) { try { monitor.wait(); } catch (InterruptedException e) { e.printStackTrace(); continue; } if (runnable != null) { runnable.run(); runnable = null; } } } }); thread.start(); } public static void execute(Runnable runnable) { AsyncExecutorWaitNotify.runnable = runnable; synchronized (monitor) { monitor.notify(); } }} -
可重入锁
public class AsyncExecutorLockCondition { private static final ReentrantLock lock = new ReentrantLock(); private static final Condition cond = lock.newCondition(); private static Thread thread; private static Runnable runnable; static { thread = new Thread(() -> { while(true){ try { lock.lock(); cond.await(); runnable.run(); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.start(); } public static void execute(Runnable runnable) { AsyncExecutorLockCondition.runnable = runnable; lock.lock(); cond.signal(); lock.unlock(); }}
【问题讨论】:
-
Re,“理想情况下,线程应该等待/睡眠,唤醒以执行任何接收到的 Runnable 对象并重新进入睡眠状态。”你所描述的正是
ThreadPoolExecutor中的工作线程所做的。 -
@besmirched 这样两个顺序调用将在两个不同的线程上执行,不是吗?
-
我不知道“这样”是什么意思。我要说的是,您的所有三个示例看起来都在尝试重新创建
java.util.concurrent.ThreadPoolExecutor类已经为您所做的事情。 -
P.S.;如果您将
ThreadPoolExecutor配置为只有一个工作线程,这将保证您提交的任务将按照您提交的顺序一个接一个地执行。静态函数java.util.concurrent.Executors.newSingleThreadExecutor()正是为此目的而存在的。
标签: java android multithreading thread-sleep reentrantlock