我正在跟踪这段代码,并试图弄清楚它究竟应该做什么。我无法让它在 IntelliJ 上运行。即使我定义了 Project SDK,运行选项也是灰色的。但我只想知道代码应该做什么。
我刚刚读了一些关于线程的理论。它是否应该在不同线程上显示每条消息 100 次并带有时间戳? Runnable 4 是如何正确使用 lambda 的示例?
主类
import java.util.Date;
import java.util.concurrent.*;
public class Example02
{
public static void main(String []args)
{
// create runnables
PrintMessageRunnable pmRunnable1 = new PrintMessageRunnable("Runnable 1");
PrintMessageRunnable pmRunnable2 = new PrintMessageRunnable("Runnable 2");
PrintMessageRunnable pmRunnable3 = new PrintMessageRunnable("Runnable 3");
// passing a runnable using Lambda notation
Runnable pmRunnable4 = () -> {
// this is the code inside the run method
String message = "Lambda Runnable";
int REPETITIONS = 100;
int DELAY = 100;
try {
for(int i = 1; i <= REPETITIONS; i++) {
Date now = new Date();
System.out.println(now + ": " + message + "." + i);
Thread.sleep(DELAY);
}
}
catch (InterruptedException e) {
System.out.println("Runnable version interrupted.");
}
};
// specify how many threads the executor service should manage
int MAX_THREADS = 2;
ExecutorService pool = Executors.newFixedThreadPool(MAX_THREADS);
// start running
pool.execute(pmRunnable1);
pool.execute(pmRunnable2);
pool.execute(pmRunnable3);
pool.execute(pmRunnable4);
}
}
打印消息可运行类
import java.util.*;
public class PrintMessageRunnable implements Runnable
{
private String message;
private int REPETITIONS = 100;
private int DELAY = 100;
public PrintMessageRunnable(String message){
this.message = message;
}
public void run(){
try {
for(int i = 1; i <= REPETITIONS; i++) {
Date now = new Date();
System.out.println(now + ": " + message + "." + i);
Thread.sleep(DELAY);
}
}
catch (InterruptedException e) {
System.out.println("Runnable version interrupted.");
}
}
}
最佳答案
在您的示例中,您有 2 个线程打印带有时间戳的消息。 runnable 的 lambda 表达式也是正确的。
但是 java.util.Date
的使用是危险的,因为它不是线程安全的。
在多线程应用程序中使用 LocalDateTime
以避免错误
关于Java 多线程示例在不同线程上打印消息 100 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46725484/