【问题标题】:How can I get Main Thread from Thread.currentThread()?如何从 Thread.currentThread() 获取主线程?
【发布时间】:2015-02-19 11:17:31
【问题描述】:

对不起,我有一个愚蠢的问题。

我有两个线程。 Thread_Main 和 Thread_Simple,在 Thread_Main 中执行方法 A() 和方法 B()。在 Thread_Simple 中执行方法 C()。现在:first performed method A(), then performed method C(), then performed method B(), then performed method A(), then performed method C(), then method B(), ...

但我想要:first performed method A(), then performed method B(), then performed method C(), then A(), B(), C(), ... 怎么办?我只能访问 Thread_Simple (Thread.currentThread()),如何从 Thread.currentThread() 获取 Thread_Main?

【问题讨论】:

  • 你的问题很抽象:/
  • 如果事情必须以特定的串行顺序运行,那么你为什么首先使用线程?
  • 当你想要 Sequential Order 时,那么使用线程的目的是什么?改用顺序代码.......
  • 如果您想确保方法 A()、B() 和 C() 以特定顺序依次调用,方法是从单个线程中调用它们。线程仅在可以以任何顺序安全执行某些操作的程序中才有用。线程之间总会有一些同步,但是你使用的越多,你从线程中获得的好处就越少。如果您强制所有线程以锁步方式运行,那么您将无法从线程中获得任何好处,但您仍然会承担与线程相关的许多风险。

标签: java multithreading synchronization android-espresso


【解决方案1】:

这通常使用线程锁来完成。这强制执行一个线程中的所有方法,然后才能执行另一个线程。你能提供代码吗?也有点困惑,你只能访问一个线程是什么意思?

【讨论】:

    【解决方案2】:

    您可以为此使用 join 方法。

    public class Test {
    public static void main(String[] args) {
    ThreadSample threadSample=new ThreadSample();
    threadSample.start();
    }
    }
    
    class Sample{
    //Function a
    public static void a(){
        System.out.println("func a");
    }
    //Function b
    public static void b(){
        System.out.println("func b");
    }
    //Function c
    public static void c(){
        System.out.println("func c");
    }
    }
    
    class ThreadSample extends Thread{
    @Override
    public void run() {
        ThreadMain threadMain=new ThreadMain();
        threadMain.start();
        try {
            threadMain.join();
        } catch (InterruptedException e) {
            //handle InterruptedException
        }
        //call function c
        Sample.c();
    }
    }
    class ThreadMain extends Thread{
    @Override
    public void run() {
    
        //call function a
        Sample.a();
        //call function b
        Sample.b();
    }
    }
    

    输出:

    func a
    func b
    func c
    

    【讨论】:

    • 您确定在sqeuential order 中编写代码将强制Threads 到maintian 顺序......?如果在方法 a() 的执行过程中发生上下文切换并且方法 b() 开始执行
    • 因为函数 a() 和 b() 都是从同一线程的 run 方法中调用的。因此,它们将保持调用它们的顺序。
    • 你是想说如果'方法a'需要15秒来执行,那么你的线程将在调用方法b之前等待'15秒'......是时候复习一些基本的了java技能
    • 是的。不管 a() 需要多长时间,b() 只会在 a() 完成后开始。
    • multithreading environment 中,并不总是只有 single thread ,是的,所有方法调用都在同一线程的 run method 中,但如果只有单线程,那么你是对的甚至不需要加入,把所有method's call相同的run方法按顺序执行。您可以使用自己的示例进行检查。希望你明白我想解释的重点
    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多