有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从线程获取主线程。currentThread()?

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

我有两条线。Thread_Main和Thread_Simple,在Thread_Main中执行方法A()和方法B()。在线程_中,简单执行方法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\u Simple(Thread.currentThread()),如何从Thread获取Thread\u Main。currentThread()


共 (2) 个答案

  1. # 1 楼答案

    这通常是使用线程锁完成的。这将强制一个线程中的所有方法在另一个线程可以执行之前完成。你能提供代码吗?还有一点困惑,你说你只能访问一个线程是什么意思

  2. # 2 楼答案

    您可以为此使用联接方法

    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