• コンストラクター/配列/Thread
    package com.sendaoi;
     
    // Thread を継承したクラス MyThread
    class MyThread extends Thread{
    	public String s ;	// 表示用文字列 s
     
    	//コンストラクター
    	public MyThread(String s) {
    		// 引数の文字列 s を 表示用文字列 s に保存
    		this.s = s ;
    	}
    	public void run() {
    		// 20回処理する
    		for(int i = 0;i < 20;i++) {
    			// 表示用文字列 s に 何回目の処理かの変数 i を結合して表示
    			System.out.print(this.s+"_"+i+" ") ;
    		}
    	}
    }
     
    // Runnable インタフェースを実装したクラス MyRunnable
    class MyRunnable implements Runnable {
    	public String s ;	// 表示用文字列 s
     
    	// コンストラクター
    	public MyRunnable(String s) {
    		// 引数の文字列 s を 表示用文字列 s に保存
    		this.s = s ;
    	}
    	public void run() {
    		// 20回処理する
    		for(int i = 0;i < 20;i++) {
    			// 表示用文字列 s に 何回目の処理かの変数 i を結合して表示
    			System.out.print(this.s+"_"+i+" ") ;		
    		}
    	}
    }
    public class ThreadTest {
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// MyThreadオブジェクトを作成して配列に保存
    		MyThread mt[] = {
    			new MyThread("T1"),
    			new MyThread("T2"),
    			new MyThread("T3"),
    			new MyThread("T4"),
    		} ;
    		// MyRunnableオブジェクトを作成して配列に保存
    		MyRunnable mr[] = {
    			new MyRunnable("R1"),
    			new MyRunnable("R2"),
    			new MyRunnable("R3"),
    			new MyRunnable("R4"),
    		} ;
     
    		// MyRunnableオブジェクトの配列から Threadオブジェクトの配列を作成
    		Thread t[] = {
    			new Thread(mr[0]),
    			new Thread(mr[1]),
    			new Thread(mr[2]),
    			new Thread(mr[3]),
    		} ;
     
    		// MyThreadオブジェクトのスレッドを全て開始
    		for (int i = 0; i < mt.length; i++) {
    				mt[i].start();
    		}
     
    		// Threadオブジェクト(MyRunnableオブジェクト)のスレッドを全て開始
    		for (int i = 0; i < t.length; i++) {
    			t[i].start();
    		}
    	}
    }
最終更新:2011年05月08日 12:25