英文:
How to print an array of strings with threads
问题
我有一个 String
数组:
String[] messages = new String[]{"aaaa", "bbbb", "cccc"};
如何通过单独的线程打印它的每个值?每个值对应一个线程。线程的数量与数组中的字符串数量相同。谢谢!
我只有一个用于这个任务的线程类:
class Worker extends Thread{
}
英文:
I have a String
array:
String[] messages = new String[]{"aaaa", "bbbb", "cccc"};
How do I print every value of it by separate threads? Every value is one thread. Threads are created the same amount as strings in array. Thanks!
I have only one class of Thread for this:
class Worker extends Thread{
}
答案1
得分: 2
Iterate over each element of the array and construct a Worker
from each one. The Worker
class should override the run
method to print the String.
class Worker extends Thread {
private String message;
public Worker(final String message) {
this.message = message;
}
@Override
public void run() {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
String[] messages = new String[]{"aaaa", "bbbb", "cccc"};
for (final String message : messages) {
new Worker(message).start();
}
}
}
英文:
Iterate over each element of the array and construct a Worker
from each one. The Worker
class should override the run
method to print the String.
class Worker extends Thread{
private String message;
public Worker(final String message){
this.message = message;
}
@Override
public void run(){
System.out.println(message);
}
}
public class Main {
public static void main(String[] args){
String[] messages = new String[]{"aaaa", "bbbb", "cccc"};
for(final String message: messages){
new Worker(message).start();
}
}
}
答案2
得分: 2
使用执行器服务而不是扩展Thread
执行器框架被添加到Java中,以减轻我们应用程序程序员处理线程的负担。请参阅教程。
从Executors
获取一个执行器服务。
ExecutorService es = Executors.newCachedThreadPool();
将您的任务编写为Runnable
的实现。请注意,与您的代码不同,我们不扩展Thread
。
String[] messages = new String[]{"aaaa", "bbbb", "cccc"};
for (String message : messages) {
es.submit(
() -> {
System.out.println(message);
}
);
}
在上面的代码中,我们使用lambda语法。您也可以使用传统语法。
当使用多个线程的线程池运行时,任务执行的顺序是不确定的。例如,运行时输出可能如下所示:
aaaa
cccc
bbbb
String[] messages = new String[]{"aaaa", "bbbb", "cccc"};
for (String message : messages) {
es.submit(
new Runnable() {
@Override
public void run() {
System.out.println(message);
}
}
);
}
顺便说一下,在Java中,列表通常比数组更方便。
List<String> messages = List.of("aaaa", "bbbb", "cccc");
for (String message : messages) {
es.submit(
() -> {
System.out.println(message);
}
);
}
查看这个完整的示例类在IdeOne.com上运行。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
System.out.println("Starting. " + Instant.now());
ExecutorService es = Executors.newCachedThreadPool();
List<String> messages = List.of("aaaa", "bbbb", "cccc");
for (String message : messages) {
es.submit(
() -> {
System.out.println(message);
}
);
}
System.out.println("Tasks submitted to executor service. " + Instant.now());
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(3));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done. " + Instant.now());
}
}
英文:
Executor service rather than extending Thread
The Executors framework was added to Java to relieve us app programmers of juggling threads. See tutorial.
Get an executor service from Executors
.
ExecutorService es = Executors.newCachedThreadPool() ;
Write your task as implementation of Runnable
.
Notice that we are not extending Thread
, in contrast to your code.
String[] messages = new String[]{ "aaaa" , "bbbb" , "cccc" } ;
for( String message : messages )
{
es.submit(
() -> { System.out.println( message ) ; }
) ;
}
In that code above, we use lambda syntax. You could just as well use traditional syntax.
When run using a thread pool of more than one thread, the order in which the tasks are executed is indeterminate. For example, when run the output may appear like this:
>aaaa
>cccc
>bbbb
String[] messages = new String[]{ "aaaa" , "bbbb" , "cccc" } ;
for ( String message : messages )
{
es.submit(
new Runnable()
{
@Override
public void run ( )
{
System.out.println( message );
}
}
);
}
By the way, lists are generally more convenient than arrays in Java.
List< String > messages = List.of( "aaaa" , "bbbb" , "cccc" ) ;
for( String message : messages )
{
es.submit(
() -> { System.out.println( message ) ; }
)
}
See this entire example class run live at IdeOne.com.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.Instant ;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println( "Starting. " + Instant.now() );
ExecutorService es = Executors.newCachedThreadPool();
List < String > messages = List.of( "aaaa" , "bbbb" , "cccc" );
for ( String message : messages )
{
es.submit(
( ) -> { System.out.println( message ); }
);
}
System.out.println( "Tasks submitted to executor service. " + Instant.now() );
try
{
Thread.sleep( TimeUnit.SECONDS.toMillis( 3 ) );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
System.out.println( "Done. " + Instant.now() );
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论