package net.studyinghttp; public class ThreadTester { // メイン関数 public static void main(String[] args) { // インスタンスを生成 MyThread1 th1 = new MyThread1(); MyThread2 th2 = new MyThread2(); // スレッドを開始 th1.startThread(); th2.startThread(); } } // Threadクラスを継承してスレッドを実現するクラス class MyThread1 extends Thread { // カウンタ int cnt = 0; /** * スレッド内の処理を記述 * @param なし */ public void run() { for(int i=0;i<10;i++) { System.out.print (++cnt); System.out.println(": This is MyThread1"); // プリエンプト try { sleep(500); } catch (Exception ex) { } } } /** * スレッドを開始するためのメソッド * @param なし */ public void startThread() { this.start(); } } // Runnableインタフェースを実装してスレッドを実現するクラス class MyThread2 implements Runnable { // カウンタ int cnt = 0; // 継承しない場合はインスタンスを作っておく Thread thread = new Thread(this); /** * スレッド内の処理を記述 * @param なし */ public void run() { for(int i=0;i<10;i++) { System.out.print (++cnt); System.out.println(": This is MyThread2"); // プリエンプト try { thread.sleep(500); } catch (Exception ex) { } } } /** * スレッドを開始するためのメソッド * @param なし */ public void startThread() { thread.start(); } }