051-マルチスレッド-マルチスレッドのサンプル 【新人エンジニアが最初に覚えたい100のJava文法】

ユーチューブ動画

マルチスレッドについて解説します。

ソースコード

public class ThreadTest {
	public static void main(String[] args) {
		Thread thread1 = new Thread(new Thread1());
		Thread thread2 = new Thread(new Thread2());
		thread1.start();
		thread2.start();
	}
}

class Thread1 implements Runnable {
	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Thread1");
		}
	}
}

class Thread2 implements Runnable {
	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Thread2");
		}
	}
}

このサンプルコードをJavaタッチタイプゲームとして遊ぶことができます。