每次我都需要创建数量不确定的线程变量。
我通过创建线程数组并创建多个线程来实现这一点。
但是,我不明白如何启动这些n个线程以表现出多线程的概念。 我希望它们能够并行运行。
如果有什么需要做的,请指导我在这种情况下做什么。
但是,我不明白如何启动这些n个线程以表现出多线程的概念。 我希望它们能够并行运行。
如果有什么需要做的,请指导我在这种情况下做什么。
但是,我不知道如何启动这些 n 个线程以实现多线程概念。我希望它们可以并行运行。
您可以使用循环创建一个线程数组:
Thread[] threads = new Thread[NUM_JOBS_TO_CREATE];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
// some code to run in parallel
// this could also be another class that implements Runnable
}
});
threads[i].start();
}
这将导致线程在后台并行运行。您随后可以与它们连接以等待它们全部完成,然后再继续。
// wait for the threads running in the background to finish
for (Thread thread : threads) {
thread.join();
}
不过,我建议您使用内置的Java Executors
而不是自己管理线程。它们会为您完成所有这些操作,并且更易于管理。使用此方法的一个好处是将任务与运行它们的线程分开。例如,您可以启动10个线程并行运行1000s和1000s的任务。
以下是一些示例ExecutorService
代码:
// create a pool of threads, 10 max jobs will execute in parallel
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// submit jobs to be executing by the pool
for (int i = 0; i < NUM_JOBS_TO_CREATE; i++) {
threadPool.submit(new Runnable() {
public void run() {
// some code to run in parallel
// this could also be another class that implements Runnable
}
});
}
// once you've submitted your last job to the service it should be shut down
threadPool.shutdown();
// wait for the threads to finish if necessary
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
查看Java线程执行器的教程获取更多信息。
基本伪代码:
create x threads, store them in an array or list;
for each thread in the list/array
call start() on the thread object;
private static final ExecutorService executor = Executors.newCachedThreadPool();
在Java 8及以上版本中,我使用lambda表达式来在新线程中运行所需内容:executor.submit(() -> {
myOtherClass.myFunction(doSomething);
});
使用newCachedThreadPool
,Java将根据系统上的CPU核心数来管理线程的总数,并在一段时间内自动停止它们(默认为60
秒)。
Scanner reader = new Scanner(System.in);
System.out.println("Enter a positive number: ");
int n = reader.nextInt();
if(n>0){
Thread[] ob = new Thread[n];
for (int i = 0; i < ob.length; i++) {
int num = i+1;
ob[i] = new Thread(new Runnable() {
public void run() {
System.out.println("Hello, I am Thread #"+num);
}
});
ob[i].start();
}
}else{
System.out.println("Please Enter A Positive Integer");
}
Runnable
生产者比消费者快得多。 - Gray