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

一曲冷凌霜 提交于 2019-12-13 05:43:32

问题


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


来源:https://stackoverflow.com/questions/28604984/how-can-i-get-main-thread-from-thread-currentthread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!