Java 线程数组?
因此,我在理解如何避免线程的顺序执行时遇到了一个问题。我试图创建一个线程数组,并在单独的循环中执行start()和join()函数。下面是我现在拥有的代码示例:Java 线程数组?,java,multithreading,Java,Multithreading,因此,我在理解如何避免线程的顺序执行时遇到了一个问题。我试图创建一个线程数组,并在单独的循环中执行start()和join()函数。下面是我现在拥有的代码示例: private static int[] w; static class wThreads implements Runnable { private final int i; public wThreads(int i) { this.i = i;
private static int[] w;
static class wThreads implements Runnable {
private final int i;
public wThreads(int i) {
this.i = i;
}
//Set member values to 1
@Override
public void run() {
//doing specific stuff here
}
}
以下是在main中创建线程的位置:
int argSize = Integer.parseInt(args[0]);
w = new int[argSize];
//Initialize w
for (int i = 0; i < argSize; i++) {
wThreads wt = new wThreads(i);
for (int j = 0; j < argSize - 1; j++) {
Thread t = new Thread(wt);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
int argSize=Integer.parseInt(args[0]);
w=新整数[argSize];
//初始化w
for(int i=0;i
显然这不是线程并行工作的例子。他们正在等待对方完成。我知道join()和start()调用应该在不同的循环中,但是如何在不同的循环中引用线程,而不是在最初创建线程的循环中引用线程
我是否需要在类声明中创建线程数组?环路也应该在那里,并且在主环路之外吗
我很困惑,请提供任何信息。谢谢大家!
我是否需要在类声明中创建线程数组
您需要一个数组或其他集合。无需将其置于类声明级别-它很可能是本地的:
w = new int[argSize];
//Initialize w
Thread[] t = new Thread[argSize];
// Create and start threads in the first loop
for (int i = 0; i < argSize; i++) {
t[i] = new Thread(new wThreads(i));
t[i].start();
}
// Let the threads run concurrently,
// and wait for them to finish in a second loop
for (int i = 0; i < argSize; i++) {
try {
t[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
w=newint[argSize];
//初始化w
线程[]t=新线程[argSize];
//在第一个循环中创建并启动线程
for(int i=0;i
在线程上调用join()
时,告诉程序等待线程执行完毕,然后销毁线程。显然,然后,我们想要启动一组新线程,让它们运行,然后再加入它们。线程和其他线程一样只是一个值,可以将其存储在变量中。因此,在本例中,让我们创建一个新的线程数组:
Thread[] myThreads; // New array of threads
myThreads = new Thread[argSize]; // Same size as our int array
for (int i = 0; i < argSize; i++) {
wThreads wt = new wThreads(i);
// you don't need the second loop.
myThreads[i] = new Thread(wt);
t.start(); // Spins up a new thread and runs your code
}
这将依次连接每个线程。发生这种情况时,如果其他线程仍在运行,则它们(可能,取决于调度程序)仍将并行运行 您不能在启动它们的循环中进行连接(您可以,但正如您所发现的,没有并行性)。为线程创建一个数组,在一个循环中启动它们,然后创建执行join调用的第二个循环。我认为你根本不想要内心世界
Thread myThreads[] = new Thread[argsize];
for (int j = 0; j < argSize; j++) {
myThreads[j] = new Thread(new wThreads(j));
myThreads[j].start();
}
for (int j = 0; j < argSize; j++) {
myThreads[j].join(); //todo add catch exception
}
threads[]=新线程[argsize];
对于(int j=0;j
我想您可能想自己做这件事,但标准的方法是使用Executor、线程池等,请参见我认为您的做法是正确的。您可以在
for
循环之外的任何位置创建线程数组(甚至线程列表)。是的,将它们收集到一个数组中。或者使用ExecutorService并等待终止()。
Thread myThreads[] = new Thread[argsize];
for (int j = 0; j < argSize; j++) {
myThreads[j] = new Thread(new wThreads(j));
myThreads[j].start();
}
for (int j = 0; j < argSize; j++) {
myThreads[j].join(); //todo add catch exception
}