for (int j = 0; j < 100; ++j)
{
GetHttpThread t = new GetHttpThread(urlList.get(j).toString());
t.start();
}例子如上,这个循环好了后,下面怎么写语句来判断这些线程都已经执行结束了啊,谢谢
{
GetHttpThread t = new GetHttpThread(urlList.get(j).toString());
t.start();
}例子如上,这个循环好了后,下面怎么写语句来判断这些线程都已经执行结束了啊,谢谢
谁写一个,
假如我在main中一个全局变量 globe=100;
那么在void run()
{
这里怎么对这个globe进行操作啊,尤其是怎么用sychronized,大侠帮忙解答
}
/**
* Creates ten threads to search for the maximum value of a large matrix.
* Each thread searches one portion of the matrix.
*/
public class TenThreads { private static class WorkerThread extends Thread {
int max = Integer.MIN_VALUE;
int[] ourArray; public WorkerThread(int[] ourArray) {
this.ourArray = ourArray;
} // Find the maximum value in our particular piece of the array
public void run() {
for (int i = 0; i < ourArray.length; i++)
max = Math.max(max, ourArray[i]);
} public int getMax() {
return max;
}
} public static void main(String[] args) {
WorkerThread[] threads = new WorkerThread[10];
int[][] bigMatrix = getBigHairyMatrix();
int max = Integer.MIN_VALUE;
// Give each thread a slice of the matrix to work with
for (int i=0; i < 10; i++) {
threads[i] = new WorkerThread(bigMatrix[i]);
threads[i].start();
} // Wait for each thread to finish
try {
for (int i=0; i < 10; i++) {
threads[i].join();
max = Math.max(max, threads[i].getMax());
}
}
catch (InterruptedException e) {
// fall through
} System.out.println("Maximum value was " + max);
}
}
int g;
Globe(int g){
this.g=g;
}
public sychronized int endThread(){
g--;
}
}
在run最后调用endThread();修改globe,在主线程中查看globe的植如果为0,就全部结束。
List threadList = new ArrayList();
for (int j = 0; j < 100; ++j)
{GetHttpThread t = new GetHttpThread(urlList.get(j).toString());
t.start();
threadList.add(t);
}for(int i=0;i<threadList.size();i++){
Thread t = (Thread)threadList.get(i);
t.join();
}
这样,每一个join都会等待该线程结束。当下面那个循环执行完的时候,那么所有线程就都结束了。还有一个方法就是利用回调。正如楼上所说就可以了。每一个执行线程在run方法的最后都去回调主线程的一个计数器方法。