问题 - 创建N个线程(例如3,名称可以是Thread-1,Thread-2,Thread-3),它们会以相反的顺序说出HelloWorld,即First Thread-3会说HelloWorld,然后是Thread-2然后是Thread -1
解决方案 - 上述问题可以通过各种方式解决,例如使用volatile标志来指示必须运行哪个线程或使用join方法(以便Thread-1完成依赖于Thread-2和Thread-2&s;线程3)。 我试图通过join方法解决这个问题。但它没有给我正确的结果。请帮我。以下是我的计划 -
Thread [] previosThread = {null};
int[] previousIndex = {0};
for (int i=3; i>=1; i--) {
int currentIndex = i;
System.out.print("PreviousIndex--"+previousIndex[0]+" ; ");
System.out.println("CurrentIndex--"+currentIndex);
Thread newThread = new Thread("Thread-"+i) {
public void run() {
if(previousIndex[0]!=0 && previousIndex[0]==currentIndex+1) {
try {
previosThread[0].join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(this.getName()+" is saying HelloWorld!!");
}
};
previosThread[0] = newThread;
previousIndex[0] = currentIndex;
newThread.start();
}
以上程序给出了不确定的输出,如下所示 -
PreviousIndex - 0; CURRENTINDEX - 3 PreviousIndex - 3; CURRENTINDEX - 2 PreviousIndex - 2; CURRENTINDEX - 1 Thread-2说HelloWorld !! Thread-1正在说HelloWorld !! Thread-3正在说HelloWorld !!
答案 0 :(得分:0)
Andreas'评论,我错误地使用了previosThread [0]。我没有使用previosThread [0],而是维护了一个单独的创建线程数组,这样我就可以在新线程上正确调用join方法,然后以相反的顺序启动这个数组的每个线程,以便正确地处理join方法,这两个调用方都是和依赖的线程应该运行。以下是我的代码---
public class AntThread extends Thread {
private Thread dependentThread;
private String threadName;
private int index;
public AntThread(Thread dependentThread, String threadName, int index) {
super(threadName);
this.dependentThread = dependentThread;
this.threadName = threadName;
this.index = index;
}
public void run() {
if(dependentThread!=null) {
try {
dependentThread.join();
} catch (InterruptedException e) {
this.interrupt();
}
}
System.out.println(Thread.currentThread().getName()+" is saying - HelloWorld");
}
}
和主要类 -
public class MultipleThreadsGreetingInReverseOrderTest {
public static void main(String[] args) throws InterruptedException {
int size = 10;
Thread [] createdThreads = new Thread[size];
for(int i=size; i>0; i--) {
Thread dependentThread = null;
if(i!=size)
dependentThread = createdThreads[i];
Thread antThread = new AntThread(dependentThread, "Thread-"+i, i);
createdThreads[i-1] = antThread;
}
//Starting the last thread first, as the join condition will work only when dependent thread is runnning
for(int j=createdThreads.length-1; j>=0; j--) {
createdThreads[j].start();
}
}
}
非常感谢Andreas !!为了快速回应。