マルチスレッド - multi-threading(Java 第8回)

はじめに

第8回はマルチスレッドである。
まずはスレッドの意味から丁寧に理解した後に、マルチスレッドを理解するという流れです。

スレッドとは

スレッドとは、プログラム内で独立して動作する一つの処理フローのこと。 OSからプロセスに割り当てられたリソースともいえる。

具体例(Thread classから)

class MyThread extends Thread {
    public void run() {
        System.out.println("This is a thread.");
    }
}

MyThread myThread = new MyThread();
myThread.start();

マルチスレッドとは

マルチスレッドとは、一つのプログラムで複数のスレッドが動作することである。
マルチスレッドのメリットは、
- プログラムの応答性の向上
- プロセッサのリソースを有効利用
- 並列処理(Concurrency)の実現

2つ例を挙げます。
1つ目はマルチスレッドを使う例です。2つの処理を2つの異なるクラスのスレッドで処理しています。
2つ目はマルチスレッドを使わないで、2つの処理を実行する例です。mainメソッド内に直接2つの処理を記述しています。
具体例
マルチスレッドを使う例

public class MultiThreadExample {
    public static void main(String[] args) {
        // Create a new thread by extending the Thread class
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 1: " + i);
            }
        });

        // Start the first thread
        thread1.start();

        // Create a second thread by implementing the Runnable interface
        Runnable runnable = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 2: " + i);
            }
        };

        // Create a new thread using the Runnable object
        Thread thread2 = new Thread(runnable);

        // Start the second thread
        thread2.start();
    }
}

マルチスレッドを使わない例

ublic class SequentialExecutionExample {
    public static void main(String[] args) {
        // First action: Print numbers from 0 to 4
        for (int i = 0; i < 5; i++) {
            System.out.println("Action 1: " + i);
        }

        // Second action: Print numbers from 5 to 9
        for (int j = 5; j < 10; j++) {
            System.out.println("Action 2: " + j);
        }
    }
}

まとめ

マルチスレッドを使わない例をあえて挙げて説明してみましたがどうでしょうか汗
第9回は入出力・ファイル操作です。

注意

このページは大学のJavaの授業の予習で書いています。
直観的な理解をメモしているだけなので、厳密なところでは誤りがあるかもしれません。