溫馨提示×

Java console.log在多線程環(huán)境中的使用

小樊
83
2024-09-06 23:13:02
欄目: 編程語言

在Java中,console.log這個概念并不存在。但是,如果你想在多線程環(huán)境中打印日志,可以使用System.out.println()方法。為了避免多線程環(huán)境下的日志輸出混亂,你可以使用synchronized關(guān)鍵字來確保每次只有一個線程能夠輸出日志。

下面是一個簡單的示例,展示了如何在多線程環(huán)境中使用System.out.println()

public class MultiThreadedLogging {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> log("Hello from thread 1"));
        Thread thread2 = new Thread(() -> log("Hello from thread 2"));

        thread1.start();
        thread2.start();
    }

    private static synchronized void log(String message) {
        System.out.println(message);
    }
}

在這個示例中,我們創(chuàng)建了兩個線程,分別輸出不同的消息。我們使用synchronized關(guān)鍵字修飾log()方法,以確保在多線程環(huán)境下,每次只有一個線程能夠輸出日志。這樣可以避免日志輸出混亂的問題。

0