Java 多线程示例在不同线程上打印消息 100 次?

标签 java multithreading intellij-idea

我正在跟踪这段代码,并试图弄清楚它究竟应该做什么。我无法让它在 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/

相关文章:

Java - 匿名类是否是静态的

java - 如何在可变参数中测试 arg

c++ - 使用 IOCP 时从两个线程调用 WSASend() 和 WSARecv() 是否安全?

ruby - 命名参数在 Intellij for Ruby 2.x 中被标记为错误的问题

java - com.mongodb.client.MongoClient 和 com.mongodb.MongoClient 的区别

java - InputStream 和 BufferedImage 之间的转换

Python/线程/屏障 : Is this a correct usage of Barrier?

c# - for 循环问题中的 System.Threading.Tasks

java - 何时使用 @NotNull 和 @Nullable IntelliJ 注释?

java - Intellij IDEA 无法打开调试器端口(localhost :8787): java. io.IOException "handshake failed - connection prematurally closed"