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