2
我在追踪这段代码,我试图弄清楚它应该做什么。我无法让它在IntelliJ上运行。即使我定义了Project SDK,运行选项也是灰色的。但我只想知道代码应该做什么。Java多线程示例在不同线程上打印100次消息?
我刚刚读了一些关于线程的理论。是不是应该在不同的线程上用时间戳显示每条消息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.");
}
}
}
谢谢:)我只是在阅读有关使用锁使线程安全的事情。现在就通过举例说明。 – Torque
单个'Date'实例在这里不会被多个线程使用。所以这是非常安全的。 – Henry
如果一个对象实例不被多个线程使用,则不需要考虑线程安全。 – Alex