简体   繁体   中英

How can I get Main Thread from Thread.currentThread()?

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()?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM