Each time I have to create a variable number of threads. I do this by creating an array of Threads and create multiple number of threads.
每次我都要创建可变数量的线程。我通过创建一个线程数组和创建多个线程来实现这一点。
But, I don't understand how to start these n number of threads behaving like multi threading concept. I want them to run in parallel.
但是,我不知道如何开始这些n个线程的行为,就像多线程的概念一样。我想让它们平行运行。
Please guide if what to do in this senario.
请指导一下在这个游戏里该怎么做。
4 个解决方案
#1
34
But, I don't understand how to start these n number of threads behaving like multi threading concept. I want them to run in parallel.
但是,我不知道如何开始这些n个线程的行为,就像多线程的概念一样。我想让它们平行运行。
You can certainly create an array of threads using a loop:
您当然可以使用循环创建一个线程数组:
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();
}
This will cause the threads to run in the background in parallel. You can then join with them later to wait for them all to complete before continuing.
这会导致线程在后台并行运行。然后,您可以稍后加入它们,在继续之前等待它们全部完成。
// wait for the threads running in the background to finish
for (Thread thread : threads) {
thread.join();
}
But instead of managing the threads yourself, I would recommend using the builtin Java Executors
. They do all of this for you are are easier to manage. One of the benefits of this method is that it separates the tasks from the threads that run them. You can start, for example, 10 threads to run 1000s and 1000s of tasks in parallel.
但是,与其自己管理线程,不如使用内置的Java执行程序。他们做了所有这些,因为你更容易管理。这种方法的好处之一是将任务与运行任务的线程分开。例如,可以从10个线程开始并行运行1000s和1000s任务。
Here's some sample ExecutorService
code:
下面是一些示例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);
For more info, see the Java tutorial on the thread executors.
有关更多信息,请参见线程执行器上的Java教程。
#2
2
Basic psuedocode:
基本psuedocode:
create x threads, store them in an array or list;
for each thread in the list/array
call start() on the thread object;
#3
2
Try very hard to not create arrays of threads and attempt to manage them - it will soon turn in to an apalling mess. If you need a pool of threads to run tasks, you need a producer-consumer queue. Create one and pass it, (or the threadpool object instance that contains it as a member), into the threads as you create them. The threads loop round, fetching tasks and executing them.
尽量不要创建线程数组并尝试管理它们——它很快就会变成一团乱麻。如果需要一个线程池来运行任务,则需要一个生产者-消费者队列。创建一个并在创建线程时将它(或作为成员包含它的threadpool对象实例)传递到线程中。线程循环,获取任务并执行它们。
The easy way to do this is to use an ExecutorService as detailed by @Gray, (+1).
实现这一点的简单方法是使用@Gray详细描述的ExecutorService(+1)。
For emphasis, I say again, don't try to micro-manage threads in arrays, lists or vectors, starting them, checking their state in a 'boss/management' loop, terminating/aborting them, destroying them etc. etc. It's like a Porsche 911 - after the expenditure of a huge amount of money/time to get one, you will have something that seems to work OK and then it will suddenly break and spin you into a tree.
再次强调,我说,不要试图面面俱到的管理线程数组,列表或向量,从他们开始,检查他们的国家在一个“老板/管理”循环,终止/中止他们,破坏他们等等。这就像一辆保时捷911 -后支出一大笔钱/时间,你会有什么,似乎工作好,然后它会突然打破,旋转你成一棵树。
Use a dedicated thread for jobs that block for extended periods, a threadpool for those that can be done intensively and quickly.
为长时间阻塞的作业使用专用线程,为那些可以快速集中完成的作业使用线程池。
#4
0
In a class that needs to be multithreaded I set at the top of the class:
在需要多线程的类中,我在类的顶部设置:
private static final ExecutorService executor = Executors.newCachedThreadPool();
私有静态最终ExecutorService executor = Executors.newCachedThreadPool();
& in Java 8+ use a lamda expression wherever I need something to run in a new thread:
在Java 8+中,只要我需要在新线程中运行什么,就使用lamda表达式:
executor.submit(() -> {
myOtherClass.myFunction(doSomething);
});
With a newCachedThreadPool
Java will manage the total number of threads according to the number of cpu cores on the system & automatically stop them after a period of inactivity (60
seconds by default).
使用newCachedThreadPool, Java将根据系统上cpu内核的数量来管理线程的总数,并在一段时间内(默认为60秒)自动停止线程。
#1
34
But, I don't understand how to start these n number of threads behaving like multi threading concept. I want them to run in parallel.
但是,我不知道如何开始这些n个线程的行为,就像多线程的概念一样。我想让它们平行运行。
You can certainly create an array of threads using a loop:
您当然可以使用循环创建一个线程数组:
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();
}
This will cause the threads to run in the background in parallel. You can then join with them later to wait for them all to complete before continuing.
这会导致线程在后台并行运行。然后,您可以稍后加入它们,在继续之前等待它们全部完成。
// wait for the threads running in the background to finish
for (Thread thread : threads) {
thread.join();
}
But instead of managing the threads yourself, I would recommend using the builtin Java Executors
. They do all of this for you are are easier to manage. One of the benefits of this method is that it separates the tasks from the threads that run them. You can start, for example, 10 threads to run 1000s and 1000s of tasks in parallel.
但是,与其自己管理线程,不如使用内置的Java执行程序。他们做了所有这些,因为你更容易管理。这种方法的好处之一是将任务与运行任务的线程分开。例如,可以从10个线程开始并行运行1000s和1000s任务。
Here's some sample ExecutorService
code:
下面是一些示例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);
For more info, see the Java tutorial on the thread executors.
有关更多信息,请参见线程执行器上的Java教程。
#2
2
Basic psuedocode:
基本psuedocode:
create x threads, store them in an array or list;
for each thread in the list/array
call start() on the thread object;
#3
2
Try very hard to not create arrays of threads and attempt to manage them - it will soon turn in to an apalling mess. If you need a pool of threads to run tasks, you need a producer-consumer queue. Create one and pass it, (or the threadpool object instance that contains it as a member), into the threads as you create them. The threads loop round, fetching tasks and executing them.
尽量不要创建线程数组并尝试管理它们——它很快就会变成一团乱麻。如果需要一个线程池来运行任务,则需要一个生产者-消费者队列。创建一个并在创建线程时将它(或作为成员包含它的threadpool对象实例)传递到线程中。线程循环,获取任务并执行它们。
The easy way to do this is to use an ExecutorService as detailed by @Gray, (+1).
实现这一点的简单方法是使用@Gray详细描述的ExecutorService(+1)。
For emphasis, I say again, don't try to micro-manage threads in arrays, lists or vectors, starting them, checking their state in a 'boss/management' loop, terminating/aborting them, destroying them etc. etc. It's like a Porsche 911 - after the expenditure of a huge amount of money/time to get one, you will have something that seems to work OK and then it will suddenly break and spin you into a tree.
再次强调,我说,不要试图面面俱到的管理线程数组,列表或向量,从他们开始,检查他们的国家在一个“老板/管理”循环,终止/中止他们,破坏他们等等。这就像一辆保时捷911 -后支出一大笔钱/时间,你会有什么,似乎工作好,然后它会突然打破,旋转你成一棵树。
Use a dedicated thread for jobs that block for extended periods, a threadpool for those that can be done intensively and quickly.
为长时间阻塞的作业使用专用线程,为那些可以快速集中完成的作业使用线程池。
#4
0
In a class that needs to be multithreaded I set at the top of the class:
在需要多线程的类中,我在类的顶部设置:
private static final ExecutorService executor = Executors.newCachedThreadPool();
私有静态最终ExecutorService executor = Executors.newCachedThreadPool();
& in Java 8+ use a lamda expression wherever I need something to run in a new thread:
在Java 8+中,只要我需要在新线程中运行什么,就使用lamda表达式:
executor.submit(() -> {
myOtherClass.myFunction(doSomething);
});
With a newCachedThreadPool
Java will manage the total number of threads according to the number of cpu cores on the system & automatically stop them after a period of inactivity (60
seconds by default).
使用newCachedThreadPool, Java将根据系统上cpu内核的数量来管理线程的总数,并在一段时间内(默认为60秒)自动停止线程。