本文介绍了如何从Thread.currentThread()获取主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am sorry, I have stupid question.

我有两个线程. 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(), ...

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(), ...

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

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

推荐答案

您可以为此使用join方法.

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

输出:

func a
func b
func c

这篇关于如何从Thread.currentThread()获取主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:17