[英]Java - Is this method multithreaded?
First of all, thanks for taking time to read this.首先,感谢您花时间阅读本文。 The code is written and executed as a JUnit test, so I dont know whether that affects the answer.代码是作为JUnit测试编写和执行的,所以我不知道这是否会影响答案。
@Test
public void generate___() {
long startTime = System.nanoTime();
for (File file : getResultsFromFolder("C:\\temp\\....")) {
class runnableClass implements Runnable{
public void run() {
// do something with file
}
}
new runnableClass().run();
}
long endTime = System.nanoTime();
System.out.println("total took: " + (endTime - startTime) / 1000000); //divide by 1000000 to get milliseconds.
}
No it is not.不,不是。
new runnableClass().run();
This calls the run
method directly as defined above it.这会直接调用上面定义的run
方法。
If you want this code to be multithreaded you will need to use:如果您希望此代码是多线程的,则需要使用:
new Thread(new runnableClass()).start();
No, the runnable will be executed by the main caller thread, just like this:不,runnable 将由主调用者线程执行,就像这样:
for (File file : getResultsFromFolder("C:\\temp\\....")) {
// do something with file
}
To make it multi-threaded, you can create new threads and call start()
:要使其成为多线程,您可以创建新线程并调用start()
:
for (final File file : getResultsFromFolder("C:\\temp\\....")) {
class runnableClass implements Runnable{
public void run() {
// do something with file
}
}
new Thread(new runnableClass()).start();
}
This method is not multi threaded due to the creation of Runnable instance in your method.由于在您的方法中创建了 Runnable 实例,此方法不是多线程的。
Example to showcase answer:展示答案的示例:
Code代码
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
myRunnable.run();
}
}
Output输出
main
main
main
main
main
main
main
main
main
main
To make this method multi threaded you could use an ExecutorService.要使此方法多线程,您可以使用 ExecutorService。
Code代码
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
Runnable myRunnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
executorService.execute(myRunnable);
}
executorService.shutdown();
}
Output输出
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
As a complement see this tutorial, it explains well what you want to know.作为补充,请参阅本教程,它很好地解释了您想知道的内容。 And it has example它有例子
https://www.tutorialspoint.com/java/java_multithreading.htm https://www.tutorialspoint.com/java/java_multithreading.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.