【问题标题】:How to create a base thread class to run method async with thread如何创建一个基线程类以与线程异步运行方法
【发布时间】:2017-04-29 06:53:38
【问题描述】:

我想创建基类以将任何函数发送给它以使用线程调用。 基于 AsyncTask 功能,我不能使用它,因为我不仅会从 Main Activity 调用另一个线程中的线程。 这是我的示例代码 在

安卓

public class BaseThread {
    public static Thread call(Function threadMethod)
    {
        Thread thread = new Thread()
        {
            @Override
            public void run()
            {
                threadMethod();
            }
        };
        thread.start();
        return thread;
    }
    public static Thread Call(Function threadMethod, Object parameter)
    {
        Thread thread = new Thread(threadMethod);
        thread.start();
        return thread;
    }
    public static void sleep(int millisecondsTimeout)
    {
        try {
            Thread.sleep(millisecondsTimeout);
        }
        catch (InterruptedException ex)
        {
           ///TODO Handle Exception and Logging
        }
    }
}

c# 中的示例:

internal class BaseThread
{
    public static Thread Call(ThreadStart threadMethod)
    {
        Thread thread = new Thread(threadMethod);
        thread.Start();
        return thread;
    }
    public static Thread Call(ParameterizedThreadStart threadMethod, object parameter)
    {
        Thread thread = new Thread(threadMethod);
        thread.Start(parameter);
        return thread;
    }
    public static void Sleep(int millisecondsTimeout)
    {
        Thread.Sleep(millisecondsTimeout);
    }
}

应该在方法中设置哪种类型的变量而不是这一行:

call(Function threadMethod)

什么是最佳实践而不是这个基类?

【问题讨论】:

    标签: android multithreading android-asynctask runnable


    【解决方案1】:

    实际上 Thread 可以被视为“基线程类”,因为您可以通过将 Runnable/Callable 实现放入构造函数来实现这种行为。将逻辑放入runnable的run方法中。但我强烈建议你不要使用纯线程,看看 ExecutorService。祝你好运。

    【讨论】:

      【解决方案2】:

      Android 有一个非常方便的类 HandlerThread。您可以创建自定义线程并将 Runnables 发布到它。它有一个嵌入的消息队列,每一个消息都是按顺序处理的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-09
        • 2012-10-13
        • 2013-04-21
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        相关资源
        最近更新 更多