我知道现在回答这个问题有点晚了。但就在昨天,我才遇到这个问题。所以我想永远不会太晚.. ;)
正如@afsantos 提到的,解决方案是在两个线程之间拥有一个共享对象并在共享对象上实现互斥。共享对象可以由两个线程交替锁定。两种可能的实现方式如下。这实际上更像是@afsantos 解决方案的扩展。特此承认他的工作。
解决方案 1:将要共享的对象的蓝图如下。
public class MutEx {
public int whoGoes, howMany;
public MutEx(int whoGoes, int howMany) {
this.whoGoes = whoGoes;
this.howMany = howMany;
}
public synchronized void switchTurns(){
this.whoGoes = (this.whoGoes + 1) % 2;
notifyAll();
}
public synchronized void waitForTurn(int id) throws InterruptedException{
while(this.whoGoes != id)
wait();
}
}
然后,您可以按如下方式实现 ClassX。
public class ClassX implements Runnable {
private final int MY_ID;
private final MutEx MUT_EX;
public ThreadOne(int MY_ID, MutEx MUT_EX) {
this.MY_ID = MY_ID;
this.MUT_EX = MUT_EX;
}
@Override
public void run(){
this.doTheWork();
}
public void doTheWork(){
for(int i = 0; i < 10; i++){
try {
MUT_EX.waitForMyTurn(MY_ID);
System.out.println("This is A and B");
MUT_EX.switchTurns();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ClassY 也将是相同的,无论您需要有什么不同。然后,在调用中(即在 main 方法中),
public static void main(String[] args) {
MutEx mutEx = new MutEx(0, 2);
Thread t1 = new Thread(new ClassX(0, mutEx);
Thread t2 = new Thread(new ClassY(1, mutEx));
t1.start();
t2.start();
}
瞧!您有两个线程,根据需要在每个线程之间交替。
解决方案 2:或者,您可以按如下方式实现 ClassX 和 ClassY。
public class ClassX extends Thread{
在这里,您将子类化java.lang.Thread
以实现您的要求。要调用它,请按如下方式更改 main 方法。
public static void main(String[] args) {
MutEx mutEx = new MutEx(0, 2);
ClassX t1 = new ClassX(0, mutEx);
ClassY t2 = new ClassY(1, mutEx);
t1.start();
t2.start();
}
运行这个,你会得到同样的结果。