2017-10-13 4 views
2

私はこのコードをトレースしていますが、私はそれが何をすべきかを理解しようとしています。私はIntelliJ上で実行することはできません。私がProject SDKを定義していても、実行オプションはグレー表示されています。しかし、私はちょうどコードが何をすべきかを知りたい。Javaマルチスレッドの印刷例のメッセージは、異なるスレッドで100回ですか?

私はちょうどスレッドの理論を少し読んでいます。タイムスタンプを付けて各メッセージを100回異なるスレッドに表示することになっていますか? Runnable 4はラムダを正しい方法で実行する方法の一例です。あなたの例では

メインクラス

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); 
    } 
} 

印刷メッセージのRunnableクラス

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."); 
     } 
    } 
} 

答えて

1

あなたは、タイムスタンプとあなたのメッセージを出力2つのスレッドを持っています。 実行可能ファイルのラムダ表示も正しいです。

しかし、java.util.Dateの使用は危険です。その理由はスレッドセーフではありません。 をマルチスレッドアプリケーションで使用すると、エラーを避けることができます

+0

ありがとうございます。今すぐその例を見てみましょう。 – Torque

+0

単一の「Date」インスタンスは、ここでは複数のスレッドによって使用されることはありません。これは完全に安全です。 – Henry

+0

オブジェクトインスタンスが複数のスレッドで使用されていない場合、実際にスレッドセーフについて考える必要はありません。 – Alex

関連する問題