簡體   English   中英

如何從Thread.currentThread()獲取主線程?

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

對不起,我有愚蠢的問題。

我有兩個主題。 Thread_Main中的Thread_Main和Thread_Simple執行方法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?

這通常使用線程鎖完成。 這將強制執行一個線程中的所有方法,然后才能執行另一個線程。 你能提供代碼嗎?還有點混淆,你的意思是你只能訪問一個線程?

你可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM