How can I get Main Thread from Thread.currentThrea

2019-09-02 08:20发布

问题:

I am sorry, I have stupid question.

I have two threads. Thread_Main and Thread_Simple, in Thread_Main performed method A() and method B(). In Thread_Simple performed method C(). Now: first performed method A(), then performed method C(), then performed method B(), then performed method A(), then performed method C(), then method B(), ...

But I want: first performed method A(), then performed method B(), then performed method C(), then A(), B(), C(), ... How can to do it? I just have access to Thread_Simple (Thread.currentThread()), How can I get Thread_Main from Thread.currentThread()?

回答1:

This is normally done using a thread lock. This enforces all the Methods in one thread to be completed before another thread can be executed. Can you provide code ?also slightly confused, what do you mean by you only have access to one thread?



回答2:

you can use join method for this.

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();
}
}

output:

func a
func b
func c