[英]How to make multiple Threads run at the same time using a for loop in Java?
I'm pretty new to java and started building a small program to find prime numbers in a given range.我对 java 很陌生,并开始构建一个小程序来查找给定范围内的素数。 Now I tried to implement multitasking, eg splitting the numbers to be checked into n parts that shall be checked independently.现在我尝试实现多任务处理,例如将要检查的数字分成应独立检查的 n 个部分。 I wanted to make it as flexible as possible, so I didn't specify the number of threads in the code, instead I used a prompt variable.我想让它尽可能灵活,所以我没有在代码中指定线程数,而是使用了一个提示变量。 Now, the code works, but the threads don't run parallel.现在,代码可以工作,但线程不能并行运行。
What seems to be the problem here?这里似乎有什么问题?
[...]
System.out.println("How many Threads shall be used?");
int b1 = scan.nextInt();
scan.close();
for (int i = 1; i <= b1; i++) {
long u = (q/b1)*(i-1);
long o = (q/b1)*i;
System.out.println("Thread "+i+" started.");
Thread t1 = new Thread(new thread1 (u, o, i));
t1.start();
}
class thread1 implements Runnable{
public thread1 (long a, long b, int c) {
//a= min. number, b = max. number, c=number of Thread
primefinder.findPrimes(b,a, c);
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
From the javadochttps://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html :从 javadochttps://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html :
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
Your logic must be in the run() method.您的逻辑必须在 run() 方法中。 It's this method that will be called and run on another thread.正是这个方法将被调用并在另一个线程上运行。 With your actual code, you do the calculation in the Runnable's constructor, which is called in your for loop, and therefor is sequential.使用您的实际代码,您可以在 Runnable 的构造函数中进行计算,该构造函数在您的 for 循环中调用,因此是顺序的。
Moving your calculation to the run method will solve the problem.将您的计算移至运行方法将解决问题。
As the correct Answer by Daniel says, you need to move your business logic into the run
method of a Runnable
, or the call
method of a Callable
.正如Daniel 的正确答案所说,您需要将业务逻辑移动到Runnable
的run
方法或Callable
的call
方法中。
Also, in modern Java we rarely address the Thread
class directly.此外,在现代 Java 中,我们很少直接处理Thread
class。 Instead use the Executors framework.而是使用 Executors 框架。
ExecutorService es = Executors.newFixedThreadPool( x ) ;
for( … ) { es.submit( task ) ; }
es.shutdown() ;
es.awaitTermination( … ) ;
This has been covered many times already on Stack Overflow.这已经在 Stack Overflow 上讨论过很多次了。 So search to learn more.因此,搜索以了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.