由主线程

时间:2017-05-02 09:50:49

标签: java android multithreading

我想让主线程命令一个单独的运行线程来执行一个方法。重要的是,单独的线程是调用方法的线程,它不能在主线程上执行。

我做了一个测试程序正在做我想要的,但我非常怀疑它是否稳定并且想知道是否有更好或者更正确的方法来做到这一点。

以下是代码:

Class Main.java

public class Main
{
    public static void main(String[] args)
    {
        SomeThread thread = new SomeThread();
        thread.start();

        try { Thread.sleep(100); } catch (InterruptedException e) {}
        // Manual wait ^, simulating that something should be done at a specific time
        thread.somethingShouldBeDone();

        thread.interrupt();

        // The thread is interrupted, nothing should be done
        thread.nothingShouldBeDone();
    }
}

Class SomeThread.java

public class SomeThread extends Thread
{
    private boolean doSomething = false;
    private boolean safeInterrupted = false;

    @Override
    public void run()
    {
        while (!safeInterrupted)
        {
            // System.out.println(new Date().getTime() + " - " + doSomething);
            if (doSomething)
            {
                doSomething();
                doSomething = false;
            }

            try { sleep(10); } catch (InterruptedException e) {}
        }
    }

    private void doSomething()
    {
        System.out.println(new Date().getTime() + " - Thread did something - " + Thread.currentThread().getId());
    }

    void somethingShouldBeDone()
    {
        System.out.println(new Date().getTime() + " - Something should be done");
        doSomething = true;
    }

    void nothingShouldBeDone()
    {
        doSomething = true;
    }

    @Override
    public void interrupt()
    {
        System.out.println(new Date().getTime() + " - Interrupting");
        try { sleep(11); } catch (InterruptedException e) {}
        safeInterrupted = true;
        super.interrupt();
        System.out.println(new Date().getTime() + " - Interrupted");
    }
}

(我遇到了isInterrupted()的问题,这就是我在这里使用变量safeInterrupted的原因..)

提前感谢您的任何答案或指导。

1 个答案:

答案 0 :(得分:0)

您可以使用Android处理程序执行此任务。

DELETE