对不起,我有一个愚蠢的问题。
我有两个主题。 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?
答案 0 :(得分:0)
这通常使用线程锁完成。这将强制执行一个线程中的所有方法,然后才能执行另一个线程。你能提供代码吗?还有点混淆,你的意思是你只能访问一个帖子吗?
答案 1 :(得分:0)
你可以使用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